home *** CD-ROM | disk | FTP | other *** search
/ EuroCD 3 / EuroCD 3.iso / Programming / Python1.4_Source / Python / compile.c < prev    next >
C/C++ Source or Header  |  1998-06-24  |  66KB  |  3,015 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Compile an expression node to intermediate code */
  33.  
  34. /* XXX TO DO:
  35.    XXX Compute maximum needed stack sizes while compiling;
  36.    XXX   then frame object can be one malloc and no stack checks are needed
  37.    XXX add __doc__ attribute == co_doc to code object attributes
  38.    XXX don't execute doc string
  39.    XXX Generate simple jump for break/return outside 'try...finally'
  40.    XXX get rid of SET_LINENO instructions, use JAR's table trick
  41.    XXX   (need an option to put them back in, for debugger!)
  42.    XXX other JAR tricks?
  43. */
  44.  
  45. #ifndef NO_PRIVATE_NAME_MANGLING
  46. #define PRIVATE_NAME_MANGLING
  47. #endif
  48.  
  49. #include "allobjects.h"
  50.  
  51. #include "node.h"
  52. #include "token.h"
  53. #include "graminit.h"
  54. #include "compile.h"
  55. #include "opcode.h"
  56. #include "structmember.h"
  57.  
  58. #include <ctype.h>
  59. #include <errno.h>
  60.  
  61. #include "protos/compile_protos.h"
  62.  
  63. #define OP_DELETE 0
  64. #define OP_ASSIGN 1
  65. #define OP_APPLY 2
  66.  
  67. #define OFF(x) offsetof(codeobject, x)
  68.  
  69. static struct memberlist code_memberlist[] = {
  70.     {"co_argcount",    T_INT,        OFF(co_argcount),    READONLY},
  71.     {"co_nlocals",    T_INT,        OFF(co_nlocals),    READONLY},
  72.     {"co_flags",    T_INT,        OFF(co_flags),        READONLY},
  73.     {"co_code",    T_OBJECT,    OFF(co_code),        READONLY},
  74.     {"co_consts",    T_OBJECT,    OFF(co_consts),        READONLY},
  75.     {"co_names",    T_OBJECT,    OFF(co_names),        READONLY},
  76.     {"co_varnames",    T_OBJECT,    OFF(co_varnames),    READONLY},
  77.     {"co_filename",    T_OBJECT,    OFF(co_filename),    READONLY},
  78.     {"co_name",    T_OBJECT,    OFF(co_name),        READONLY},
  79.     {NULL}    /* Sentinel */
  80. };
  81.  
  82. static object *
  83. code_getattr(co, name)
  84.     codeobject *co;
  85.     char *name;
  86. {
  87.     return getmember((char *)co, code_memberlist, name);
  88. }
  89.  
  90. static void
  91. code_dealloc(co)
  92.     codeobject *co;
  93. {
  94.     XDECREF(co->co_code);
  95.     XDECREF(co->co_consts);
  96.     XDECREF(co->co_names);
  97.     XDECREF(co->co_filename);
  98.     XDECREF(co->co_name);
  99.     XDECREF(co->co_varnames);
  100.     DEL(co);
  101. }
  102.  
  103. static object *
  104. code_repr(co)
  105.     codeobject *co;
  106. {
  107.     char buf[500];
  108.     int lineno = -1;
  109.     char *p = GETSTRINGVALUE(co->co_code);
  110.     char *filename = "???";
  111.     char *name = "???";
  112.     if (*p == SET_LINENO)
  113.         lineno = (p[1] & 0xff) | ((p[2] & 0xff) << 8);
  114.     if (co->co_filename && is_stringobject(co->co_filename))
  115.         filename = getstringvalue(co->co_filename);
  116.     if (co->co_name && is_stringobject(co->co_name))
  117.         name = getstringvalue(co->co_name);
  118.     sprintf(buf, "<code object %.100s at %lx, file \"%.300s\", line %d>",
  119.         name, (long)co, filename, lineno);
  120.     return newstringobject(buf);
  121. }
  122.  
  123. static int
  124. code_compare(co, cp)
  125.     codeobject *co, *cp;
  126. {
  127.     int cmp;
  128.     cmp = cp->co_argcount - cp->co_argcount;
  129.     if (cmp) return cmp;
  130.     cmp = cp->co_nlocals - cp->co_nlocals;
  131.     if (cmp) return cmp;
  132.     cmp = cp->co_flags - cp->co_flags;
  133.     if (cmp) return cmp;
  134.     cmp = cmpobject((object *)co->co_code, (object *)cp->co_code);
  135.     if (cmp) return cmp;
  136.     cmp = cmpobject(co->co_consts, cp->co_consts);
  137.     if (cmp) return cmp;
  138.     cmp = cmpobject(co->co_names, cp->co_names);
  139.     if (cmp) return cmp;
  140.     cmp = cmpobject(co->co_varnames, cp->co_varnames);
  141.     return cmp;
  142. }
  143.  
  144. static long
  145. code_hash(co)
  146.     codeobject *co;
  147. {
  148.     long h, h1, h2, h3, h4;
  149.     h1 = hashobject((object *)co->co_code);
  150.     if (h1 == -1) return -1;
  151.     h2 = hashobject(co->co_consts);
  152.     if (h2 == -1) return -1;
  153.     h3 = hashobject(co->co_names);
  154.     if (h3 == -1) return -1;
  155.     h4 = hashobject(co->co_varnames);
  156.     if (h4 == -1) return -1;
  157.     h = h1 ^ h2 ^ h3 ^ h4 ^
  158.         co->co_argcount ^ co->co_nlocals ^ co->co_flags;
  159.     if (h == -1) h = -2;
  160.     return h;
  161. }
  162.  
  163. typeobject Codetype = {
  164.     OB_HEAD_INIT(&Typetype)
  165.     0,
  166.     "code",
  167.     sizeof(codeobject),
  168.     0,
  169.     (destructor)code_dealloc, /*tp_dealloc*/
  170.     0,        /*tp_print*/
  171.     (getattrfunc)code_getattr, /*tp_getattr*/
  172.     0,        /*tp_setattr*/
  173.     (cmpfunc)code_compare, /*tp_compare*/
  174.     (reprfunc)code_repr, /*tp_repr*/
  175.     0,        /*tp_as_number*/
  176.     0,        /*tp_as_sequence*/
  177.     0,        /*tp_as_mapping*/
  178.     (hashfunc)code_hash, /*tp_hash*/
  179. };
  180.  
  181. codeobject *
  182. newcodeobject(argcount, nlocals, flags,
  183.           code, consts, names, varnames, filename, name)
  184.     int argcount;
  185.     int nlocals;
  186.     int flags;
  187.     object *code;
  188.     object *consts;
  189.     object *names;
  190.     object *varnames;
  191.     object *filename;
  192.     object *name;
  193. {
  194.     codeobject *co;
  195.     int i;
  196.     /* Check argument types */
  197.     if (argcount < 0 || nlocals < 0 ||
  198.         code == NULL || !is_stringobject(code) ||
  199.         consts == NULL || !is_tupleobject(consts) ||
  200.         names == NULL || !is_tupleobject(names) ||
  201.         varnames == NULL || !is_tupleobject(varnames) ||
  202.         name == NULL || !is_stringobject(name) ||
  203.         filename == NULL || !is_stringobject(filename)) {
  204.         err_badcall();
  205.         return NULL;
  206.     }
  207.     /* Make sure names and varnames are all strings */
  208.     for (i = gettuplesize(names); --i >= 0; ) {
  209.         object *v = gettupleitem(names, i);
  210.         if (v == NULL || !is_stringobject(v)) {
  211.             err_badcall();
  212.             return NULL;
  213.         }
  214.     }
  215.     for (i = gettuplesize(varnames); --i >= 0; ) {
  216.         object *v = gettupleitem(varnames, i);
  217.         if (v == NULL || !is_stringobject(v)) {
  218.             err_badcall();
  219.             return NULL;
  220.         }
  221.     }
  222.     co = NEWOBJ(codeobject, &Codetype);
  223.     if (co != NULL) {
  224.         co->co_argcount = argcount;
  225.         co->co_nlocals = nlocals;
  226.         co->co_flags = flags;
  227.         INCREF(code);
  228.         co->co_code = (stringobject *)code;
  229.         INCREF(consts);
  230.         co->co_consts = consts;
  231.         INCREF(names);
  232.         co->co_names = names;
  233.         INCREF(varnames);
  234.         co->co_varnames = varnames;
  235.         INCREF(filename);
  236.         co->co_filename = filename;
  237.         INCREF(name);
  238.         co->co_name = name;
  239.     }
  240.     return co;
  241. }
  242.  
  243.  
  244. /* Data structure used internally */
  245.  
  246. #define MAXBLOCKS 20 /* Max static block nesting within a function */
  247.  
  248. struct compiling {
  249.     object *c_code;        /* string */
  250.     object *c_consts;    /* list of objects */
  251.     object *c_names;    /* list of strings (names) */
  252.     object *c_globals;    /* dictionary (value=None) */
  253.     object *c_locals;    /* dictionary (value=localID) */
  254.     object *c_varnames;    /* list (inverse of c_locals) */
  255.     int c_nlocals;        /* index of next local */
  256.     int c_argcount;        /* number of top-level arguments */
  257.     int c_flags;        /* same as co_flags */
  258.     int c_nexti;        /* index into c_code */
  259.     int c_errors;        /* counts errors occurred */
  260.     int c_infunction;    /* set when compiling a function */
  261.     int c_interactive;    /* generating code for interactive command */
  262.     int c_loops;        /* counts nested loops */
  263.     int c_begin;        /* begin of current loop, for 'continue' */
  264.     int c_block[MAXBLOCKS];    /* stack of block types */
  265.     int c_nblocks;        /* current block stack level */
  266.     char *c_filename;    /* filename of current node */
  267.     char *c_name;        /* name of object (e.g. function) */
  268.     int c_lineno;        /* Current line number */
  269. #ifdef PRIVATE_NAME_MANGLING
  270.     char *c_private;    /* for private name mangling */
  271. #endif
  272. };
  273.  
  274.  
  275. /* Error message including line number */
  276.  
  277. static void
  278. com_error(c, exc, msg)
  279.     struct compiling *c;
  280.     object *exc;
  281.     char *msg;
  282. {
  283.     int n = strlen(msg);
  284.     object *v;
  285.     char buffer[30];
  286.     char *s;
  287.     if (c->c_lineno <= 1) {
  288.         /* Unknown line number or single interactive command */
  289.         err_setstr(exc, msg);
  290.         return;
  291.     }
  292.     sprintf(buffer, " (line %d)", c->c_lineno);
  293.     v = newsizedstringobject((char *)NULL, n + strlen(buffer));
  294.     if (v == NULL)
  295.         return; /* MemoryError, too bad */
  296.     s = GETSTRINGVALUE((stringobject *)v);
  297.     strcpy(s, msg);
  298.     strcat(s, buffer);
  299.     err_setval(exc, v);
  300.     DECREF(v);
  301.     c->c_errors++;
  302. }
  303.  
  304.  
  305. /* Interface to the block stack */
  306.  
  307. static void
  308. block_push(c, type)
  309.     struct compiling *c;
  310.     int type;
  311. {
  312.     if (c->c_nblocks >= MAXBLOCKS) {
  313.         com_error(c, SystemError, "too many statically nested blocks");
  314.     }
  315.     else {
  316.         c->c_block[c->c_nblocks++] = type;
  317.     }
  318. }
  319.  
  320. static void
  321. block_pop(c, type)
  322.     struct compiling *c;
  323.     int type;
  324. {
  325.     if (c->c_nblocks > 0)
  326.         c->c_nblocks--;
  327.     if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) {
  328.         com_error(c, SystemError, "bad block pop");
  329.     }
  330. }
  331.  
  332.  
  333. /* Prototype forward declarations */
  334.  
  335. static int com_init PROTO((struct compiling *, char *));
  336. static void com_free PROTO((struct compiling *));
  337. static void com_done PROTO((struct compiling *));
  338. static void com_node PROTO((struct compiling *, struct _node *));
  339. static void com_factor PROTO((struct compiling *, struct _node *));
  340. static void com_addbyte PROTO((struct compiling *, int));
  341. static void com_addint PROTO((struct compiling *, int));
  342. static void com_addoparg PROTO((struct compiling *, int, int));
  343. static void com_addfwref PROTO((struct compiling *, int, int *));
  344. static void com_backpatch PROTO((struct compiling *, int));
  345. static int com_add PROTO((struct compiling *, object *, object *));
  346. static int com_addconst PROTO((struct compiling *, object *));
  347. static int com_addname PROTO((struct compiling *, object *));
  348. static void com_addopname PROTO((struct compiling *, int, node *));
  349. static void com_list PROTO((struct compiling *, node *, int));
  350. static int com_argdefs PROTO((struct compiling *, node *));
  351. static int com_newlocal PROTO((struct compiling *, char *));
  352. static codeobject *icompile PROTO((struct _node *, struct compiling *));
  353. static codeobject *jcompile PROTO((struct _node *, char *, struct compiling *));
  354.  
  355. static int
  356. com_init(c, filename)
  357.     struct compiling *c;
  358.     char *filename;
  359. {
  360.     if ((c->c_code = newsizedstringobject((char *)NULL, 1000)) == NULL)
  361.         goto fail_3;
  362.     if ((c->c_consts = newlistobject(0)) == NULL)
  363.         goto fail_2;
  364.     if ((c->c_names = newlistobject(0)) == NULL)
  365.         goto fail_1;
  366.     if ((c->c_globals = newdictobject()) == NULL)
  367.         goto fail_0;
  368.     if ((c->c_locals = newdictobject()) == NULL)
  369.         goto fail_00;
  370.     if ((c->c_varnames = newlistobject(0)) == NULL)
  371.         goto fail_000;
  372.     c->c_nlocals = 0;
  373.     c->c_argcount = 0;
  374.     c->c_flags = 0;
  375.     c->c_nexti = 0;
  376.     c->c_errors = 0;
  377.     c->c_infunction = 0;
  378.     c->c_interactive = 0;
  379.     c->c_loops = 0;
  380.     c->c_begin = 0;
  381.     c->c_nblocks = 0;
  382.     c->c_filename = filename;
  383.     c->c_name = "?";
  384.     c->c_lineno = 0;
  385.     return 1;
  386.     
  387.   fail_000:
  388.       DECREF(c->c_locals);
  389.   fail_00:
  390.       DECREF(c->c_globals);
  391.   fail_0:
  392.       DECREF(c->c_names);
  393.   fail_1:
  394.     DECREF(c->c_consts);
  395.   fail_2:
  396.     DECREF(c->c_code);
  397.   fail_3:
  398.      return 0;
  399. }
  400.  
  401. static void
  402. com_free(c)
  403.     struct compiling *c;
  404. {
  405.     XDECREF(c->c_code);
  406.     XDECREF(c->c_consts);
  407.     XDECREF(c->c_names);
  408.     XDECREF(c->c_globals);
  409.     XDECREF(c->c_locals);
  410.     XDECREF(c->c_varnames);
  411. }
  412.  
  413. static void
  414. com_done(c)
  415.     struct compiling *c;
  416. {
  417.     if (c->c_code != NULL)
  418.         resizestring(&c->c_code, c->c_nexti);
  419. }
  420.  
  421. static void
  422. com_addbyte(c, byte)
  423.     struct compiling *c;
  424.     int byte;
  425. {
  426.     int len;
  427.     /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
  428.     if (byte < 0 || byte > 255) {
  429.         /*
  430.         fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
  431.         fatal("com_addbyte: byte out of range");
  432.         */
  433.         com_error(c, SystemError, "com_addbyte: byte out of range");
  434.     }
  435.     if (c->c_code == NULL)
  436.         return;
  437.     len = getstringsize(c->c_code);
  438.     if (c->c_nexti >= len) {
  439.         if (resizestring(&c->c_code, len+1000) != 0) {
  440.             c->c_errors++;
  441.             return;
  442.         }
  443.     }
  444.     getstringvalue(c->c_code)[c->c_nexti++] = byte;
  445. }
  446.  
  447. static void
  448. com_addint(c, x)
  449.     struct compiling *c;
  450.     int x;
  451. {
  452.     com_addbyte(c, x & 0xff);
  453.     com_addbyte(c, x >> 8); /* XXX x should be positive */
  454. }
  455.  
  456. static void
  457. com_addoparg(c, op, arg)
  458.     struct compiling *c;
  459.     int op;
  460.     int arg;
  461. {
  462.     if (op == SET_LINENO)
  463.         c->c_lineno = arg;
  464.     com_addbyte(c, op);
  465.     com_addint(c, arg);
  466. }
  467.  
  468. static void
  469. com_addfwref(c, op, p_anchor)
  470.     struct compiling *c;
  471.     int op;
  472.     int *p_anchor;
  473. {
  474.     /* Compile a forward reference for backpatching */
  475.     int here;
  476.     int anchor;
  477.     com_addbyte(c, op);
  478.     here = c->c_nexti;
  479.     anchor = *p_anchor;
  480.     *p_anchor = here;
  481.     com_addint(c, anchor == 0 ? 0 : here - anchor);
  482. }
  483.  
  484. static void
  485. com_backpatch(c, anchor)
  486.     struct compiling *c;
  487.     int anchor; /* Must be nonzero */
  488. {
  489.     unsigned char *code = (unsigned char *) getstringvalue(c->c_code);
  490.     int target = c->c_nexti;
  491.     int dist;
  492.     int prev;
  493.     for (;;) {
  494.         /* Make the JUMP instruction at anchor point to target */
  495.         prev = code[anchor] + (code[anchor+1] << 8);
  496.         dist = target - (anchor+2);
  497.         code[anchor] = dist & 0xff;
  498.         code[anchor+1] = dist >> 8;
  499.         if (!prev)
  500.             break;
  501.         anchor -= prev;
  502.     }
  503. }
  504.  
  505. /* Handle literals and names uniformly */
  506.  
  507. static int
  508. com_add(c, list, v)
  509.     struct compiling *c;
  510.     object *list;
  511.     object *v;
  512. {
  513.     int n = getlistsize(list);
  514.     int i;
  515.     for (i = n; --i >= 0; ) {
  516.         object *w = getlistitem(list, i);
  517.         if (v->ob_type == w->ob_type && cmpobject(v, w) == 0)
  518.             return i;
  519.     }
  520.     if (addlistitem(list, v) != 0)
  521.         c->c_errors++;
  522.     return n;
  523. }
  524.  
  525. static int
  526. com_addconst(c, v)
  527.     struct compiling *c;
  528.     object *v;
  529. {
  530.     return com_add(c, c->c_consts, v);
  531. }
  532.  
  533. static int
  534. com_addname(c, v)
  535.     struct compiling *c;
  536.     object *v;
  537. {
  538.     return com_add(c, c->c_names, v);
  539. }
  540.  
  541. #ifdef PRIVATE_NAME_MANGLING
  542. static int
  543. com_mangle(c, name, buffer, maxlen)
  544.     struct compiling *c;
  545.     char *name;
  546.     char *buffer;
  547.     int maxlen;
  548. {
  549.     /* Name mangling: __private becomes _classname__private.
  550.        This is independent from how the name is used. */
  551.     char *p;
  552.     int nlen, plen;
  553.     nlen = strlen(name);
  554.     if (nlen+2 >= maxlen)
  555.         return 0; /* Don't mangle __extremely_long_names */
  556.     if (name[nlen-1] == '_' && name[nlen-2] == '_')
  557.         return 0; /* Don't mangle __whatever__ */
  558.     p = c->c_private;
  559.     /* Strip leading underscores from class name */
  560.     while (*p == '_')
  561.         p++;
  562.     if (*p == '\0')
  563.         return 0; /* Don't mangle if class is just underscores */
  564.     plen = strlen(p);
  565.     if (plen + nlen >= maxlen)
  566.         plen = maxlen-nlen-2; /* Truncate class name if too long */
  567.     /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
  568.     buffer[0] = '_';
  569.     strncpy(buffer+1, p, plen);
  570.     strcpy(buffer+1+plen, name);
  571.     /* fprintf(stderr, "mangle %s -> %s\n", name, buffer); */
  572.     return 1;
  573. }
  574. #endif
  575.  
  576. static void
  577. com_addopnamestr(c, op, name)
  578.     struct compiling *c;
  579.     int op;
  580.     char *name;
  581. {
  582.     object *v;
  583.     int i;
  584. #ifdef PRIVATE_NAME_MANGLING
  585.     char buffer[256];
  586.     if (name != NULL && name[0] == '_' && name[1] == '_' &&
  587.         c->c_private != NULL &&
  588.         com_mangle(c, name, buffer, (int)sizeof(buffer)))
  589.         name = buffer;
  590. #endif
  591.     if (name == NULL || (v = newstringobject(name)) == NULL) {
  592.         c->c_errors++;
  593.         i = 255;
  594.     }
  595.     else {
  596.         i = com_addname(c, v);
  597.         DECREF(v);
  598.     }
  599.     /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
  600.     switch (op) {
  601.     case LOAD_NAME:
  602.     case STORE_NAME:
  603.     case DELETE_NAME:
  604.         if (dictlookup(c->c_globals, name) != NULL) {
  605.             switch (op) {
  606.             case LOAD_NAME:   op = LOAD_GLOBAL;   break;
  607.             case STORE_NAME:  op = STORE_GLOBAL;  break;
  608.             case DELETE_NAME: op = DELETE_GLOBAL; break;
  609.             }
  610.         }
  611.     }
  612.     com_addoparg(c, op, i);
  613. }
  614.  
  615. static void
  616. com_addopname(c, op, n)
  617.     struct compiling *c;
  618.     int op;
  619.     node *n;
  620. {
  621.     char *name;
  622.     char buffer[1000];
  623.     /* XXX it is possible to write this code without the 1000
  624.        chars on the total length of dotted names, I just can't be
  625.        bothered right now */
  626.     if (TYPE(n) == STAR)
  627.         name = "*";
  628.     else if (TYPE(n) == dotted_name) {
  629.         char *p = buffer;
  630.         int i;
  631.         name = buffer;
  632.         for (i = 0; i < NCH(n); i += 2) {
  633.             char *s = STR(CHILD(n, i));
  634.             if (p + strlen(s) > buffer + (sizeof buffer) - 2) {
  635.                 com_error(c, MemoryError,
  636.                       "dotted_name too long");
  637.                 name = NULL;
  638.                 break;
  639.             }
  640.             if (p != buffer)
  641.                 *p++ = '.';
  642.             strcpy(p, s);
  643.             p = strchr(p, '\0');
  644.         }
  645.     }
  646.     else {
  647.         REQ(n, NAME);
  648.         name = STR(n);
  649.     }
  650.     com_addopnamestr(c, op, name);
  651. }
  652.  
  653. static object *
  654. parsenumber(co, s)
  655.     struct compiling *co;
  656.     char *s;
  657. {
  658.     extern long mystrtol PROTO((const char *, char **, int));
  659.     extern unsigned long mystrtoul PROTO((const char *, char **, int));
  660.     extern double atof PROTO((const char *));
  661.     char *end;
  662.     long x;
  663. #ifndef WITHOUT_COMPLEX
  664.     Py_complex c;
  665.     int imflag;
  666. #endif
  667.  
  668.     errno = 0;
  669.     end = s + strlen(s) - 1;
  670. #ifndef WITHOUT_COMPLEX
  671.     imflag = *end == 'j' || *end == 'J';
  672. #endif
  673.     if (*end == 'l' || *end == 'L')
  674.         return long_scan(s, 0);
  675.     if (s[0] == '0')
  676.         x = (long) mystrtoul(s, &end, 0);
  677.     else
  678.         x = mystrtol(s, &end, 0);
  679.     if (*end == '\0') {
  680.         if (errno != 0) {
  681.             com_error(co, OverflowError,
  682.                   "integer literal too large");
  683.             return NULL;
  684.         }
  685.         return newintobject(x);
  686.     }
  687.     /* XXX Huge floats may silently fail */
  688. #ifndef WITHOUT_COMPLEX
  689.     if (imflag) {
  690.         c.real = 0.;
  691.         c.imag = atof(s);
  692.         return newcomplexobject(c);
  693.     }
  694.     else
  695. #endif
  696.         return newfloatobject(atof(s));
  697. }
  698.  
  699. static object *
  700. parsestr(s)
  701.     char *s;
  702. {
  703.     object *v;
  704.     int len;
  705.     char *buf;
  706.     char *p;
  707.     char *end;
  708.     int c;
  709.     int quote = *s;
  710.     if (quote != '\'' && quote != '\"') {
  711.         err_badcall();
  712.         return NULL;
  713.     }
  714.     s++;
  715.     len = strlen(s);
  716.     if (s[--len] != quote) {
  717.         err_badcall();
  718.         return NULL;
  719.     }
  720.     if (len >= 4 && s[0] == quote && s[1] == quote) {
  721.         s += 2;
  722.         len -= 2;
  723.         if (s[--len] != quote || s[--len] != quote) {
  724.             err_badcall();
  725.             return NULL;
  726.         }
  727.     }
  728.     if (strchr(s, '\\') == NULL)
  729.         return newsizedstringobject(s, len);
  730.     v = newsizedstringobject((char *)NULL, len);
  731.     p = buf = getstringvalue(v);
  732.     end = s + len;
  733.     while (s < end) {
  734.         if (*s != '\\') {
  735.             *p++ = *s++;
  736.             continue;
  737.         }
  738.         s++;
  739.         switch (*s++) {
  740.         /* XXX This assumes ASCII! */
  741.         case '\n': break;
  742.         case '\\': *p++ = '\\'; break;
  743.         case '\'': *p++ = '\''; break;
  744.         case '\"': *p++ = '\"'; break;
  745.         case 'b': *p++ = '\b'; break;
  746.         case 'f': *p++ = '\014'; break; /* FF */
  747.         case 't': *p++ = '\t'; break;
  748.         case 'n': *p++ = '\n'; break;
  749.         case 'r': *p++ = '\r'; break;
  750.         case 'v': *p++ = '\013'; break; /* VT */
  751.         case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  752.         case '0': case '1': case '2': case '3':
  753.         case '4': case '5': case '6': case '7':
  754.             c = s[-1] - '0';
  755.             if ('0' <= *s && *s <= '7') {
  756.                 c = (c<<3) + *s++ - '0';
  757.                 if ('0' <= *s && *s <= '7')
  758.                     c = (c<<3) + *s++ - '0';
  759.             }
  760.             *p++ = c;
  761.             break;
  762.         case 'x':
  763.             if (isxdigit(Py_CHARMASK(*s))) {
  764.                 sscanf(s, "%x", &c);
  765.                 *p++ = c;
  766.                 do {
  767.                     s++;
  768.                 } while (isxdigit(Py_CHARMASK(*s)));
  769.                 break;
  770.             }
  771.         /* FALLTHROUGH */
  772.         default: *p++ = '\\'; *p++ = s[-1]; break;
  773.         }
  774.     }
  775.     resizestring(&v, (int)(p - buf));
  776.     return v;
  777. }
  778.  
  779. static object *
  780. parsestrplus(n)
  781.     node *n;
  782. {
  783.     object *v;
  784.     int i;
  785.     REQ(CHILD(n, 0), STRING);
  786.     if ((v = parsestr(STR(CHILD(n, 0)))) != NULL) {
  787.         /* String literal concatenation */
  788.         for (i = 1; i < NCH(n) && v != NULL; i++) {
  789.             joinstring_decref(&v, parsestr(STR(CHILD(n, i))));
  790.         }
  791.     }
  792.     return v;
  793. }
  794.  
  795. static void
  796. com_list_constructor(c, n)
  797.     struct compiling *c;
  798.     node *n;
  799. {
  800.     int len;
  801.     int i;
  802.     if (TYPE(n) != testlist)
  803.         REQ(n, exprlist);
  804.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  805.     len = (NCH(n) + 1) / 2;
  806.     for (i = 0; i < NCH(n); i += 2)
  807.         com_node(c, CHILD(n, i));
  808.     com_addoparg(c, BUILD_LIST, len);
  809. }
  810.  
  811. static void
  812. com_dictmaker(c, n)
  813.     struct compiling *c;
  814.     node *n;
  815. {
  816.     int i;
  817.     /* dictmaker: test ':' test (',' test ':' value)* [','] */
  818.     for (i = 0; i+2 < NCH(n); i += 4) {
  819.         /* We must arrange things just right for STORE_SUBSCR.
  820.            It wants the stack to look like (value) (dict) (key) */
  821.         com_addbyte(c, DUP_TOP);
  822.         com_node(c, CHILD(n, i+2)); /* value */
  823.         com_addbyte(c, ROT_TWO);
  824.         com_node(c, CHILD(n, i)); /* key */
  825.         com_addbyte(c, STORE_SUBSCR);
  826.     }
  827. }
  828.  
  829. static void
  830. com_atom(c, n)
  831.     struct compiling *c;
  832.     node *n;
  833. {
  834.     node *ch;
  835.     object *v;
  836.     int i;
  837.     REQ(n, atom);
  838.     ch = CHILD(n, 0);
  839.     switch (TYPE(ch)) {
  840.     case LPAR:
  841.         if (TYPE(CHILD(n, 1)) == RPAR)
  842.             com_addoparg(c, BUILD_TUPLE, 0);
  843.         else
  844.             com_node(c, CHILD(n, 1));
  845.         break;
  846.     case LSQB:
  847.         if (TYPE(CHILD(n, 1)) == RSQB)
  848.             com_addoparg(c, BUILD_LIST, 0);
  849.         else
  850.             com_list_constructor(c, CHILD(n, 1));
  851.         break;
  852.     case LBRACE: /* '{' [dictmaker] '}' */
  853.         com_addoparg(c, BUILD_MAP, 0);
  854.         if (TYPE(CHILD(n, 1)) != RBRACE)
  855.             com_dictmaker(c, CHILD(n, 1));
  856.         break;
  857.     case BACKQUOTE:
  858.         com_node(c, CHILD(n, 1));
  859.         com_addbyte(c, UNARY_CONVERT);
  860.         break;
  861.     case NUMBER:
  862.         if ((v = parsenumber(c, STR(ch))) == NULL) {
  863.             i = 255;
  864.         }
  865.         else {
  866.             i = com_addconst(c, v);
  867.             DECREF(v);
  868.         }
  869.         com_addoparg(c, LOAD_CONST, i);
  870.         break;
  871.     case STRING:
  872.         v = parsestrplus(n);
  873.         if (v == NULL) {
  874.             c->c_errors++;
  875.             i = 255;
  876.         }
  877.         else {
  878.             i = com_addconst(c, v);
  879.             DECREF(v);
  880.         }
  881.         com_addoparg(c, LOAD_CONST, i);
  882.         break;
  883.     case NAME:
  884.         com_addopname(c, LOAD_NAME, ch);
  885.         break;
  886.     default:
  887.         fprintf(stderr, "node type %d\n", TYPE(ch));
  888.         com_error(c, SystemError, "com_atom: unexpected node type");
  889.     }
  890. }
  891.  
  892. static void
  893. com_slice(c, n, op)
  894.     struct compiling *c;
  895.     node *n;
  896.     int op;
  897. {
  898.     if (NCH(n) == 1) {
  899.         com_addbyte(c, op);
  900.     }
  901.     else if (NCH(n) == 2) {
  902.         if (TYPE(CHILD(n, 0)) != COLON) {
  903.             com_node(c, CHILD(n, 0));
  904.             com_addbyte(c, op+1);
  905.         }
  906.         else {
  907.             com_node(c, CHILD(n, 1));
  908.             com_addbyte(c, op+2);
  909.         }
  910.     }
  911.     else {
  912.         com_node(c, CHILD(n, 0));
  913.         com_node(c, CHILD(n, 2));
  914.         com_addbyte(c, op+3);
  915.     }
  916. }
  917.  
  918. static int
  919. com_argument(c, n, inkeywords)
  920.     struct compiling *c;
  921.     node *n; /* argument */
  922.     int inkeywords;
  923. {
  924.     node *m;
  925.     REQ(n, argument); /* [test '='] test; really [ keyword '='] keyword */
  926.     if (NCH(n) == 1) {
  927.         if (inkeywords) {
  928.             com_error(c, SyntaxError,
  929.                    "non-keyword arg after keyword arg");
  930.         }
  931.         else {
  932.             com_node(c, CHILD(n, 0));
  933.         }
  934.         return 0;
  935.     }
  936.     m = n;
  937.     do {
  938.         m = CHILD(m, 0);
  939.     } while (NCH(m) == 1);
  940.     if (TYPE(m) != NAME) {
  941.         com_error(c, SyntaxError, "keyword can't be an expression");
  942.     }
  943.     else {
  944.         object *v = newstringobject(STR(m));
  945.         if (v == NULL)
  946.             c->c_errors++;
  947.         else {
  948.             com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  949.             DECREF(v);
  950.         }
  951.     }
  952.     com_node(c, CHILD(n, 2));
  953.     return 1;
  954. }
  955.  
  956. static void
  957. com_call_function(c, n)
  958.     struct compiling *c;
  959.     node *n; /* EITHER arglist OR ')' */
  960. {
  961.     if (TYPE(n) == RPAR) {
  962.         com_addoparg(c, CALL_FUNCTION, 0);
  963.     }
  964.     else {
  965.         int inkeywords, i, na, nk;
  966.         REQ(n, arglist);
  967.         inkeywords = 0;
  968.         na = 0;
  969.         nk = 0;
  970.         for (i = 0; i < NCH(n); i += 2) {
  971.             inkeywords = com_argument(c, CHILD(n, i), inkeywords);
  972.             if (!inkeywords)
  973.                 na++;
  974.             else
  975.                 nk++;
  976.         }
  977.         if (na > 255 || nk > 255) {
  978.             com_error(c, SyntaxError, "more than 255 arguments");
  979.         }
  980.         com_addoparg(c, CALL_FUNCTION, na | (nk << 8));
  981.     }
  982. }
  983.  
  984. static void
  985. com_select_member(c, n)
  986.     struct compiling *c;
  987.     node *n;
  988. {
  989.     com_addopname(c, LOAD_ATTR, n);
  990. }
  991.  
  992. static void
  993. com_sliceobj(c, n)
  994.     struct compiling *c;
  995.     node *n;
  996. {
  997.     int i=0;
  998.     int ns=2; /* number of slice arguments */
  999.     int first_missing=0;
  1000.     node *ch;
  1001.  
  1002.     /* first argument */
  1003.     if (TYPE(CHILD(n,i)) == COLON) {
  1004.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1005.         i++;
  1006.     }
  1007.     else {
  1008.         com_node(c, CHILD(n,i));
  1009.         i++;
  1010.         REQ(CHILD(n,i),COLON);
  1011.         i++;
  1012.     }
  1013.     /* second argument */
  1014.     if (i < NCH(n) && TYPE(CHILD(n,i)) == test) {
  1015.         com_node(c, CHILD(n,i));
  1016.         i++;
  1017.     }
  1018.     else com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1019.     /* remaining arguments */
  1020.     for (; i < NCH(n); i++) {
  1021.         ns++;
  1022.         ch=CHILD(n,i);
  1023.         REQ(ch, sliceop);
  1024.         if (NCH(ch) == 1) {
  1025.             /* right argument of ':' missing */
  1026.             com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1027.         }
  1028.         else
  1029.             com_node(c, CHILD(ch,1));
  1030.     }
  1031.     com_addoparg(c, BUILD_SLICE, ns);
  1032. }
  1033.  
  1034. static void
  1035. com_subscript(c, n)
  1036.     struct compiling *c;
  1037.     node *n;
  1038. {
  1039.     node *ch;
  1040.     REQ(n, subscript);
  1041.     ch = CHILD(n,0);
  1042.     /* check for rubber index */
  1043.     if (TYPE(ch) == DOT && TYPE(CHILD(n,1)) == DOT)
  1044.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_Ellipsis));
  1045.     else {
  1046.         /* check for slice */
  1047.         if ((TYPE(ch) == COLON || NCH(n) > 1))
  1048.             com_sliceobj(c, n);
  1049.         else {
  1050.             REQ(ch, test);
  1051.             com_node(c, ch);
  1052.         }
  1053.     }
  1054. }
  1055.  
  1056. static void
  1057. com_subscriptlist(c, n, assigning)
  1058.     struct compiling *c;
  1059.     node *n;
  1060.     int assigning;
  1061. {
  1062.     int i, op;
  1063.     REQ(n, subscriptlist);
  1064.     /* Check to make backward compatible slice behavior for '[i:j]' */
  1065.     if (NCH(n) == 1) {
  1066.         node *sub = CHILD(n, 0); /* subscript */
  1067.         /* Make it is a simple slice.
  1068.            should have exactly one colon. */
  1069.         if ((TYPE(CHILD(sub, 0)) == COLON
  1070.              || (NCH(sub) > 1 && TYPE(CHILD(sub, 1)) == COLON))
  1071.             && (TYPE(CHILD(sub,NCH(sub)-1)) != sliceop)) {
  1072.             if (assigning == OP_APPLY)
  1073.                 op = SLICE;
  1074.             else
  1075.                 op = ((assigning == OP_ASSIGN) ? STORE_SLICE : DELETE_SLICE);
  1076.             com_slice(c, sub, op);
  1077.             return;
  1078.         }
  1079.     }
  1080.     /* Else normal subscriptlist.  Compile each subscript. */
  1081.     for (i = 0; i < NCH(n); i += 2)
  1082.         com_subscript(c, CHILD(n, i));
  1083.     /* Put multiple subscripts into a tuple */
  1084.     if (NCH(n) > 1)
  1085.         com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 2);
  1086.     if (assigning == OP_APPLY)
  1087.         op = BINARY_SUBSCR;
  1088.     else
  1089.         op = ((assigning == OP_ASSIGN) ? STORE_SUBSCR : DELETE_SUBSCR);
  1090.     com_addbyte(c, op);
  1091. }
  1092.  
  1093. static void
  1094. com_apply_trailer(c, n)
  1095.     struct compiling *c;
  1096.     node *n;
  1097. {
  1098.     REQ(n, trailer);
  1099.     switch (TYPE(CHILD(n, 0))) {
  1100.     case LPAR:
  1101.         com_call_function(c, CHILD(n, 1));
  1102.         break;
  1103.     case DOT:
  1104.         com_select_member(c, CHILD(n, 1));
  1105.         break;
  1106.     case LSQB:
  1107.         com_subscriptlist(c, CHILD(n, 1), OP_APPLY);
  1108.         break;
  1109.     default:
  1110.         com_error(c, SystemError,
  1111.               "com_apply_trailer: unknown trailer type");
  1112.     }
  1113. }
  1114.  
  1115. static void
  1116. com_power(c, n)
  1117.     struct compiling *c;
  1118.     node *n;
  1119. {
  1120.     int i;
  1121.     REQ(n, power);
  1122.     com_atom(c, CHILD(n, 0));
  1123.     for (i = 1; i < NCH(n); i++) {
  1124.         if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1125.             com_factor(c, CHILD(n, i+1));
  1126.             com_addbyte(c, BINARY_POWER);
  1127.             break;
  1128.         }
  1129.         else
  1130.             com_apply_trailer(c, CHILD(n, i));
  1131.     }
  1132. }
  1133.  
  1134. static void
  1135. com_factor(c, n)
  1136.     struct compiling *c;
  1137.     node *n;
  1138. {
  1139.     REQ(n, factor);
  1140.     if (TYPE(CHILD(n, 0)) == PLUS) {
  1141.         com_factor(c, CHILD(n, 1));
  1142.         com_addbyte(c, UNARY_POSITIVE);
  1143.     }
  1144.     else if (TYPE(CHILD(n, 0)) == MINUS) {
  1145.         com_factor(c, CHILD(n, 1));
  1146.         com_addbyte(c, UNARY_NEGATIVE);
  1147.     }
  1148.     else if (TYPE(CHILD(n, 0)) == TILDE) {
  1149.         com_factor(c, CHILD(n, 1));
  1150.         com_addbyte(c, UNARY_INVERT);
  1151.     }
  1152.     else {
  1153.         com_power(c, CHILD(n, 0));
  1154.     }
  1155. }
  1156.  
  1157. static void
  1158. com_term(c, n)
  1159.     struct compiling *c;
  1160.     node *n;
  1161. {
  1162.     int i;
  1163.     int op;
  1164.     REQ(n, term);
  1165.     com_factor(c, CHILD(n, 0));
  1166.     for (i = 2; i < NCH(n); i += 2) {
  1167.         com_factor(c, CHILD(n, i));
  1168.         switch (TYPE(CHILD(n, i-1))) {
  1169.         case STAR:
  1170.             op = BINARY_MULTIPLY;
  1171.             break;
  1172.         case SLASH:
  1173.             op = BINARY_DIVIDE;
  1174.             break;
  1175.         case PERCENT:
  1176.             op = BINARY_MODULO;
  1177.             break;
  1178.         default:
  1179.             com_error(c, SystemError,
  1180.                   "com_term: operator not *, / or %");
  1181.             op = 255;
  1182.         }
  1183.         com_addbyte(c, op);
  1184.     }
  1185. }
  1186.  
  1187. static void
  1188. com_arith_expr(c, n)
  1189.     struct compiling *c;
  1190.     node *n;
  1191. {
  1192.     int i;
  1193.     int op;
  1194.     REQ(n, arith_expr);
  1195.     com_term(c, CHILD(n, 0));
  1196.     for (i = 2; i < NCH(n); i += 2) {
  1197.         com_term(c, CHILD(n, i));
  1198.         switch (TYPE(CHILD(n, i-1))) {
  1199.         case PLUS:
  1200.             op = BINARY_ADD;
  1201.             break;
  1202.         case MINUS:
  1203.             op = BINARY_SUBTRACT;
  1204.             break;
  1205.         default:
  1206.             com_error(c, SystemError,
  1207.                   "com_arith_expr: operator not + or -");
  1208.             op = 255;
  1209.         }
  1210.         com_addbyte(c, op);
  1211.     }
  1212. }
  1213.  
  1214. static void
  1215. com_shift_expr(c, n)
  1216.     struct compiling *c;
  1217.     node *n;
  1218. {
  1219.     int i;
  1220.     int op;
  1221.     REQ(n, shift_expr);
  1222.     com_arith_expr(c, CHILD(n, 0));
  1223.     for (i = 2; i < NCH(n); i += 2) {
  1224.         com_arith_expr(c, CHILD(n, i));
  1225.         switch (TYPE(CHILD(n, i-1))) {
  1226.         case LEFTSHIFT:
  1227.             op = BINARY_LSHIFT;
  1228.             break;
  1229.         case RIGHTSHIFT:
  1230.             op = BINARY_RSHIFT;
  1231.             break;
  1232.         default:
  1233.             com_error(c, SystemError,
  1234.                   "com_shift_expr: operator not << or >>");
  1235.             op = 255;
  1236.         }
  1237.         com_addbyte(c, op);
  1238.     }
  1239. }
  1240.  
  1241. static void
  1242. com_and_expr(c, n)
  1243.     struct compiling *c;
  1244.     node *n;
  1245. {
  1246.     int i;
  1247.     int op;
  1248.     REQ(n, and_expr);
  1249.     com_shift_expr(c, CHILD(n, 0));
  1250.     for (i = 2; i < NCH(n); i += 2) {
  1251.         com_shift_expr(c, CHILD(n, i));
  1252.         if (TYPE(CHILD(n, i-1)) == AMPER) {
  1253.             op = BINARY_AND;
  1254.         }
  1255.         else {
  1256.             com_error(c, SystemError,
  1257.                   "com_and_expr: operator not &");
  1258.             op = 255;
  1259.         }
  1260.         com_addbyte(c, op);
  1261.     }
  1262. }
  1263.  
  1264. static void
  1265. com_xor_expr(c, n)
  1266.     struct compiling *c;
  1267.     node *n;
  1268. {
  1269.     int i;
  1270.     int op;
  1271.     REQ(n, xor_expr);
  1272.     com_and_expr(c, CHILD(n, 0));
  1273.     for (i = 2; i < NCH(n); i += 2) {
  1274.         com_and_expr(c, CHILD(n, i));
  1275.         if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) {
  1276.             op = BINARY_XOR;
  1277.         }
  1278.         else {
  1279.             com_error(c, SystemError,
  1280.                   "com_xor_expr: operator not ^");
  1281.             op = 255;
  1282.         }
  1283.         com_addbyte(c, op);
  1284.     }
  1285. }
  1286.  
  1287. static void
  1288. com_expr(c, n)
  1289.     struct compiling *c;
  1290.     node *n;
  1291. {
  1292.     int i;
  1293.     int op;
  1294.     REQ(n, expr);
  1295.     com_xor_expr(c, CHILD(n, 0));
  1296.     for (i = 2; i < NCH(n); i += 2) {
  1297.         com_xor_expr(c, CHILD(n, i));
  1298.         if (TYPE(CHILD(n, i-1)) == VBAR) {
  1299.             op = BINARY_OR;
  1300.         }
  1301.         else {
  1302.             com_error(c, SystemError,
  1303.                   "com_expr: expr operator not |");
  1304.             op = 255;
  1305.         }
  1306.         com_addbyte(c, op);
  1307.     }
  1308. }
  1309.  
  1310. static enum cmp_op
  1311. cmp_type(n)
  1312.     node *n;
  1313. {
  1314.     REQ(n, comp_op);
  1315.     /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
  1316.               | 'in' | 'not' 'in' | 'is' | 'is' not' */
  1317.     if (NCH(n) == 1) {
  1318.         n = CHILD(n, 0);
  1319.         switch (TYPE(n)) {
  1320.         case LESS:    return LT;
  1321.         case GREATER:    return GT;
  1322.         case EQEQUAL:            /* == */
  1323.         case EQUAL:    return EQ;
  1324.         case LESSEQUAL:    return LE;
  1325.         case GREATEREQUAL: return GE;
  1326.         case NOTEQUAL:    return NE;    /* <> or != */
  1327.         case NAME:    if (strcmp(STR(n), "in") == 0) return IN;
  1328.                 if (strcmp(STR(n), "is") == 0) return IS;
  1329.         }
  1330.     }
  1331.     else if (NCH(n) == 2) {
  1332.         switch (TYPE(CHILD(n, 0))) {
  1333.         case NAME:    if (strcmp(STR(CHILD(n, 1)), "in") == 0)
  1334.                     return NOT_IN;
  1335.                 if (strcmp(STR(CHILD(n, 0)), "is") == 0)
  1336.                     return IS_NOT;
  1337.         }
  1338.     }
  1339.     return BAD;
  1340. }
  1341.  
  1342. static void
  1343. com_comparison(c, n)
  1344.     struct compiling *c;
  1345.     node *n;
  1346. {
  1347.     int i;
  1348.     enum cmp_op op;
  1349.     int anchor;
  1350.     REQ(n, comparison); /* comparison: expr (comp_op expr)* */
  1351.     com_expr(c, CHILD(n, 0));
  1352.     if (NCH(n) == 1)
  1353.         return;
  1354.     
  1355.     /****************************************************************
  1356.        The following code is generated for all but the last
  1357.        comparison in a chain:
  1358.        
  1359.        label:    on stack:    opcode:        jump to:
  1360.        
  1361.             a        <code to load b>
  1362.             a, b        DUP_TOP
  1363.             a, b, b        ROT_THREE
  1364.             b, a, b        COMPARE_OP
  1365.             b, 0-or-1    JUMP_IF_FALSE    L1
  1366.             b, 1        POP_TOP
  1367.             b        
  1368.     
  1369.        We are now ready to repeat this sequence for the next
  1370.        comparison in the chain.
  1371.        
  1372.        For the last we generate:
  1373.        
  1374.                b        <code to load c>
  1375.                b, c        COMPARE_OP
  1376.                0-or-1        
  1377.        
  1378.        If there were any jumps to L1 (i.e., there was more than one
  1379.        comparison), we generate:
  1380.        
  1381.                0-or-1        JUMP_FORWARD    L2
  1382.        L1:        b, 0        ROT_TWO
  1383.                0, b        POP_TOP
  1384.                0
  1385.        L2:
  1386.     ****************************************************************/
  1387.     
  1388.     anchor = 0;
  1389.     
  1390.     for (i = 2; i < NCH(n); i += 2) {
  1391.         com_expr(c, CHILD(n, i));
  1392.         if (i+2 < NCH(n)) {
  1393.             com_addbyte(c, DUP_TOP);
  1394.             com_addbyte(c, ROT_THREE);
  1395.         }
  1396.         op = cmp_type(CHILD(n, i-1));
  1397.         if (op == BAD) {
  1398.             com_error(c, SystemError,
  1399.                   "com_comparison: unknown comparison op");
  1400.         }
  1401.         com_addoparg(c, COMPARE_OP, op);
  1402.         if (i+2 < NCH(n)) {
  1403.             com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1404.             com_addbyte(c, POP_TOP);
  1405.         }
  1406.     }
  1407.     
  1408.     if (anchor) {
  1409.         int anchor2 = 0;
  1410.         com_addfwref(c, JUMP_FORWARD, &anchor2);
  1411.         com_backpatch(c, anchor);
  1412.         com_addbyte(c, ROT_TWO);
  1413.         com_addbyte(c, POP_TOP);
  1414.         com_backpatch(c, anchor2);
  1415.     }
  1416. }
  1417.  
  1418. static void
  1419. com_not_test(c, n)
  1420.     struct compiling *c;
  1421.     node *n;
  1422. {
  1423.     REQ(n, not_test); /* 'not' not_test | comparison */
  1424.     if (NCH(n) == 1) {
  1425.         com_comparison(c, CHILD(n, 0));
  1426.     }
  1427.     else {
  1428.         com_not_test(c, CHILD(n, 1));
  1429.         com_addbyte(c, UNARY_NOT);
  1430.     }
  1431. }
  1432.  
  1433. static void
  1434. com_and_test(c, n)
  1435.     struct compiling *c;
  1436.     node *n;
  1437. {
  1438.     int i;
  1439.     int anchor;
  1440.     REQ(n, and_test); /* not_test ('and' not_test)* */
  1441.     anchor = 0;
  1442.     i = 0;
  1443.     for (;;) {
  1444.         com_not_test(c, CHILD(n, i));
  1445.         if ((i += 2) >= NCH(n))
  1446.             break;
  1447.         com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1448.         com_addbyte(c, POP_TOP);
  1449.     }
  1450.     if (anchor)
  1451.         com_backpatch(c, anchor);
  1452. }
  1453.  
  1454. static void
  1455. com_test(c, n)
  1456.     struct compiling *c;
  1457.     node *n;
  1458. {
  1459.     REQ(n, test); /* and_test ('and' and_test)* | lambdef */
  1460.     if (NCH(n) == 1 && TYPE(CHILD(n, 0)) == lambdef) {
  1461.         object *v;
  1462.         int i;
  1463.         int ndefs = com_argdefs(c, CHILD(n, 0));
  1464.         v = (object *) icompile(CHILD(n, 0), c);
  1465.         if (v == NULL) {
  1466.             c->c_errors++;
  1467.             i = 255;
  1468.         }
  1469.         else {
  1470.             i = com_addconst(c, v);
  1471.             DECREF(v);
  1472.         }
  1473.         com_addoparg(c, LOAD_CONST, i);
  1474.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  1475.     }
  1476.     else {
  1477.         int anchor = 0;
  1478.         int i = 0;
  1479.         for (;;) {
  1480.             com_and_test(c, CHILD(n, i));
  1481.             if ((i += 2) >= NCH(n))
  1482.                 break;
  1483.             com_addfwref(c, JUMP_IF_TRUE, &anchor);
  1484.             com_addbyte(c, POP_TOP);
  1485.         }
  1486.         if (anchor)
  1487.             com_backpatch(c, anchor);
  1488.     }
  1489. }
  1490.  
  1491. static void
  1492. com_list(c, n, toplevel)
  1493.     struct compiling *c;
  1494.     node *n;
  1495.     int toplevel; /* If nonzero, *always* build a tuple */
  1496. {
  1497.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  1498.     if (NCH(n) == 1 && !toplevel) {
  1499.         com_node(c, CHILD(n, 0));
  1500.     }
  1501.     else {
  1502.         int i;
  1503.         int len;
  1504.         len = (NCH(n) + 1) / 2;
  1505.         for (i = 0; i < NCH(n); i += 2)
  1506.             com_node(c, CHILD(n, i));
  1507.         com_addoparg(c, BUILD_TUPLE, len);
  1508.     }
  1509. }
  1510.  
  1511.  
  1512. /* Begin of assignment compilation */
  1513.  
  1514. static void com_assign_name PROTO((struct compiling *, node *, int));
  1515. static void com_assign PROTO((struct compiling *, node *, int));
  1516.  
  1517. static void
  1518. com_assign_attr(c, n, assigning)
  1519.     struct compiling *c;
  1520.     node *n;
  1521.     int assigning;
  1522. {
  1523.     com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n);
  1524. }
  1525.  
  1526. static void
  1527. com_assign_trailer(c, n, assigning)
  1528.     struct compiling *c;
  1529.     node *n;
  1530.     int assigning;
  1531. {
  1532.     REQ(n, trailer);
  1533.     switch (TYPE(CHILD(n, 0))) {
  1534.     case LPAR: /* '(' [exprlist] ')' */
  1535.         com_error(c, SyntaxError, "can't assign to function call");
  1536.         break;
  1537.     case DOT: /* '.' NAME */
  1538.         com_assign_attr(c, CHILD(n, 1), assigning);
  1539.         break;
  1540.     case LSQB: /* '[' subscriptlist ']' */
  1541.         com_subscriptlist(c, CHILD(n, 1), assigning);
  1542.         break;
  1543.     default:
  1544.         com_error(c, SystemError, "unknown trailer type");
  1545.     }
  1546. }
  1547.  
  1548. static void
  1549. com_assign_tuple(c, n, assigning)
  1550.     struct compiling *c;
  1551.     node *n;
  1552.     int assigning;
  1553. {
  1554.     int i;
  1555.     if (TYPE(n) != testlist)
  1556.         REQ(n, exprlist);
  1557.     if (assigning)
  1558.         com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2);
  1559.     for (i = 0; i < NCH(n); i += 2)
  1560.         com_assign(c, CHILD(n, i), assigning);
  1561. }
  1562.  
  1563. static void
  1564. com_assign_list(c, n, assigning)
  1565.     struct compiling *c;
  1566.     node *n;
  1567.     int assigning;
  1568. {
  1569.     int i;
  1570.     if (assigning)
  1571.         com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2);
  1572.     for (i = 0; i < NCH(n); i += 2)
  1573.         com_assign(c, CHILD(n, i), assigning);
  1574. }
  1575.  
  1576. static void
  1577. com_assign_name(c, n, assigning)
  1578.     struct compiling *c;
  1579.     node *n;
  1580.     int assigning;
  1581. {
  1582.     REQ(n, NAME);
  1583.     com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n);
  1584. }
  1585.  
  1586. static void
  1587. com_assign(c, n, assigning)
  1588.     struct compiling *c;
  1589.     node *n;
  1590.     int assigning;
  1591. {
  1592.     /* Loop to avoid trivial recursion */
  1593.     for (;;) {
  1594.         switch (TYPE(n)) {
  1595.         
  1596.         case exprlist:
  1597.         case testlist:
  1598.             if (NCH(n) > 1) {
  1599.                 com_assign_tuple(c, n, assigning);
  1600.                 return;
  1601.             }
  1602.             n = CHILD(n, 0);
  1603.             break;
  1604.         
  1605.         case test:
  1606.         case and_test:
  1607.         case not_test:
  1608.         case comparison:
  1609.         case expr:
  1610.         case xor_expr:
  1611.         case and_expr:
  1612.         case shift_expr:
  1613.         case arith_expr:
  1614.         case term:
  1615.         case factor:
  1616.             if (NCH(n) > 1) {
  1617.                 com_error(c, SyntaxError,
  1618.                       "can't assign to operator");
  1619.                 return;
  1620.             }
  1621.             n = CHILD(n, 0);
  1622.             break;
  1623.         
  1624.         case power: /* atom trailer* ('**' power)* */
  1625. /* ('+'|'-'|'~') factor | atom trailer* */
  1626.             if (TYPE(CHILD(n, 0)) != atom) {
  1627.                 com_error(c, SyntaxError,
  1628.                       "can't assign to operator");
  1629.                 return;
  1630.             }
  1631.             if (NCH(n) > 1) { /* trailer or exponent present */
  1632.                 int i;
  1633.                 com_node(c, CHILD(n, 0));
  1634.                 for (i = 1; i+1 < NCH(n); i++) {
  1635.                     if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1636.                         com_error(c, SyntaxError,
  1637.                           "can't assign to operator");
  1638.                         return;
  1639.                     }
  1640.                     com_apply_trailer(c, CHILD(n, i));
  1641.                 } /* NB i is still alive */
  1642.                 com_assign_trailer(c,
  1643.                         CHILD(n, i), assigning);
  1644.                 return;
  1645.             }
  1646.             n = CHILD(n, 0);
  1647.             break;
  1648.         
  1649.         case atom:
  1650.             switch (TYPE(CHILD(n, 0))) {
  1651.             case LPAR:
  1652.                 n = CHILD(n, 1);
  1653.                 if (TYPE(n) == RPAR) {
  1654.                     /* XXX Should allow () = () ??? */
  1655.                     com_error(c, SyntaxError,
  1656.                           "can't assign to ()");
  1657.                     return;
  1658.                 }
  1659.                 break;
  1660.             case LSQB:
  1661.                 n = CHILD(n, 1);
  1662.                 if (TYPE(n) == RSQB) {
  1663.                     com_error(c, SyntaxError,
  1664.                           "can't assign to []");
  1665.                     return;
  1666.                 }
  1667.                 com_assign_list(c, n, assigning);
  1668.                 return;
  1669.             case NAME:
  1670.                 com_assign_name(c, CHILD(n, 0), assigning);
  1671.                 return;
  1672.             default:
  1673.                 com_error(c, SyntaxError,
  1674.                       "can't assign to literal");
  1675.                 return;
  1676.             }
  1677.             break;
  1678.  
  1679.         case lambdef:
  1680.             com_error(c, SyntaxError, "can't assign to lambda");
  1681.             return;
  1682.         
  1683.         default:
  1684.             fprintf(stderr, "node type %d\n", TYPE(n));
  1685.             com_error(c, SystemError, "com_assign: bad node");
  1686.             return;
  1687.         
  1688.         }
  1689.     }
  1690. }
  1691.  
  1692. static void
  1693. com_expr_stmt(c, n)
  1694.     struct compiling *c;
  1695.     node *n;
  1696. {
  1697.     REQ(n, expr_stmt); /* testlist ('=' testlist)* */
  1698.     com_node(c, CHILD(n, NCH(n)-1));
  1699.     if (NCH(n) == 1) {
  1700.         if (c->c_interactive)
  1701.             com_addbyte(c, PRINT_EXPR);
  1702.         else
  1703.             com_addbyte(c, POP_TOP);
  1704.     }
  1705.     else {
  1706.         int i;
  1707.         for (i = 0; i < NCH(n)-2; i+=2) {
  1708.             if (i+2 < NCH(n)-2)
  1709.                 com_addbyte(c, DUP_TOP);
  1710.             com_assign(c, CHILD(n, i), OP_ASSIGN);
  1711.         }
  1712.     }
  1713. }
  1714.  
  1715. static void
  1716. com_print_stmt(c, n)
  1717.     struct compiling *c;
  1718.     node *n;
  1719. {
  1720.     int i;
  1721.     REQ(n, print_stmt); /* 'print' (test ',')* [test] */
  1722.     for (i = 1; i < NCH(n); i += 2) {
  1723.         com_node(c, CHILD(n, i));
  1724.         com_addbyte(c, PRINT_ITEM);
  1725.     }
  1726.     if (TYPE(CHILD(n, NCH(n)-1)) != COMMA)
  1727.         com_addbyte(c, PRINT_NEWLINE);
  1728.         /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
  1729. }
  1730.  
  1731. static void
  1732. com_return_stmt(c, n)
  1733.     struct compiling *c;
  1734.     node *n;
  1735. {
  1736.     REQ(n, return_stmt); /* 'return' [testlist] */
  1737.     if (!c->c_infunction) {
  1738.         com_error(c, SyntaxError, "'return' outside function");
  1739.     }
  1740.     if (NCH(n) < 2)
  1741.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1742.     else
  1743.         com_node(c, CHILD(n, 1));
  1744.     com_addbyte(c, RETURN_VALUE);
  1745. }
  1746.  
  1747. static void
  1748. com_raise_stmt(c, n)
  1749.     struct compiling *c;
  1750.     node *n;
  1751. {
  1752.     REQ(n, raise_stmt); /* 'raise' test [',' test [',' test]] */
  1753.     com_node(c, CHILD(n, 1));
  1754.     if (NCH(n) > 3) {
  1755.         com_node(c, CHILD(n, 3));
  1756.         if (NCH(n) > 5)
  1757.             com_node(c, CHILD(n, 5));
  1758.     }
  1759.     com_addoparg(c, RAISE_VARARGS, NCH(n)/2);
  1760. }
  1761.  
  1762. static void
  1763. com_import_stmt(c, n)
  1764.     struct compiling *c;
  1765.     node *n;
  1766. {
  1767.     int i;
  1768.     REQ(n, import_stmt);
  1769.     /* 'import' dotted_name (',' dotted_name)* |
  1770.        'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
  1771.     if (STR(CHILD(n, 0))[0] == 'f') {
  1772.         /* 'from' dotted_name 'import' ... */
  1773.         REQ(CHILD(n, 1), dotted_name);
  1774.         com_addopname(c, IMPORT_NAME, CHILD(n, 1));
  1775.         for (i = 3; i < NCH(n); i += 2)
  1776.             com_addopname(c, IMPORT_FROM, CHILD(n, i));
  1777.         com_addbyte(c, POP_TOP);
  1778.     }
  1779.     else {
  1780.         /* 'import' ... */
  1781.         for (i = 1; i < NCH(n); i += 2) {
  1782.             REQ(CHILD(n, i), dotted_name);
  1783.             com_addopname(c, IMPORT_NAME, CHILD(n, i));
  1784.             com_addopname(c, STORE_NAME, CHILD(CHILD(n, i), 0));
  1785.         }
  1786.     }
  1787. }
  1788.  
  1789. static void
  1790. com_global_stmt(c, n)
  1791.     struct compiling *c;
  1792.     node *n;
  1793. {
  1794.     int i;
  1795.     REQ(n, global_stmt);
  1796.     /* 'global' NAME (',' NAME)* */
  1797.     for (i = 1; i < NCH(n); i += 2) {
  1798.         char *s = STR(CHILD(n, i));
  1799. #ifdef PRIVATE_NAME_MANGLING
  1800.         char buffer[256];
  1801.         if (s != NULL && s[0] == '_' && s[1] == '_' &&
  1802.             c->c_private != NULL &&
  1803.             com_mangle(c, s, buffer, (int)sizeof(buffer)))
  1804.             s = buffer;
  1805. #endif
  1806.         if (dictlookup(c->c_locals, s) != NULL) {
  1807.             com_error(c, SyntaxError, "name is local and global");
  1808.         }
  1809.         else if (dictinsert(c->c_globals, s, None) != 0)
  1810.             c->c_errors++;
  1811.     }
  1812. }
  1813.  
  1814. static int
  1815. com_newlocal_o(c, nameval)
  1816.     struct compiling *c;
  1817.     object *nameval;
  1818. {
  1819.     int i;
  1820.     object *ival;
  1821.     if (getlistsize(c->c_varnames) != c->c_nlocals) {
  1822.         /* This is usually caused by an error on a previous call */
  1823.         if (c->c_errors == 0) {
  1824.             com_error(c, SystemError, "mixed up var name/index");
  1825.         }
  1826.         return 0;
  1827.     }
  1828.     ival = newintobject(i = c->c_nlocals++);
  1829.     if (ival == NULL)
  1830.         c->c_errors++;
  1831.     else if (mappinginsert(c->c_locals, nameval, ival) != 0)
  1832.         c->c_errors++;
  1833.     else if (addlistitem(c->c_varnames, nameval) != 0)
  1834.         c->c_errors++;
  1835.     XDECREF(ival);
  1836.     return i;
  1837. }
  1838.  
  1839. static int
  1840. com_addlocal_o(c, nameval)
  1841.     struct compiling *c;
  1842.     object *nameval;
  1843. {
  1844.     object *ival =  mappinglookup(c->c_locals, nameval);
  1845.     if (ival != NULL)
  1846.         return getintvalue(ival);
  1847.     return com_newlocal_o(c, nameval);
  1848. }
  1849.  
  1850. static int
  1851. com_newlocal(c, name)
  1852.     struct compiling *c;
  1853.     char *name;
  1854. {
  1855.     object *nameval = newstringobject(name);
  1856.     int i;
  1857.     if (nameval == NULL) {
  1858.         c->c_errors++;
  1859.         return 0;
  1860.     }
  1861.     i = com_newlocal_o(c, nameval);
  1862.     DECREF(nameval);
  1863.     return i;
  1864. }
  1865.  
  1866. #define strequ(a, b) (strcmp((a), (b)) == 0)
  1867.  
  1868. #ifdef SUPPORT_OBSOLETE_ACCESS
  1869. static void
  1870. com_access_stmt(c, n)
  1871.     struct compiling *c;
  1872.     node *n;
  1873. {
  1874.     int i, j, k, mode, imode;
  1875.     object *vmode;
  1876.     REQ(n, access_stmt);
  1877.     /* 'access' NAME (',' NAME)* ':' accesstype (',' accesstype)*
  1878.        accesstype: NAME+ */
  1879.  
  1880.     /* Find where the colon is */
  1881.     i = 1;
  1882.     while (TYPE(CHILD(n,i-1)) != COLON)
  1883.         i += 1;
  1884.  
  1885.     /* Calculate the mode mask */
  1886.     mode = 0;
  1887.     for (j = i; j < NCH(n); j += 2) {
  1888.         int r = 0, w = 0, p = 0;
  1889.         for (k = 0; k < NCH(CHILD(n,j)); k++) {
  1890.             if (strequ(STR(CHILD(CHILD(n,j),k)), "public"))
  1891.                 p = 0;
  1892.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "protected"))
  1893.                 p = 1;
  1894.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "private"))
  1895.                 p = 2;
  1896.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "read"))
  1897.                 r = 1;
  1898.             else if (strequ(STR(CHILD(CHILD(n,j),k)), "write"))
  1899.                 w = 1;
  1900.             else /* XXX should make this an exception */
  1901.                 fprintf(stderr, "bad access type %s\n",
  1902.                     STR(CHILD(CHILD(n,j),k)));
  1903.         }
  1904.         if (r == 0 && w == 0)
  1905.             r = w = 1;
  1906.         if (p == 0) {
  1907.             if (r == 1) mode |= AC_R_PUBLIC;
  1908.             if (w == 1) mode |= AC_W_PUBLIC;
  1909.         } else if (p == 1) {
  1910.             if (r == 1) mode |= AC_R_PROTECTED;
  1911.             if (w == 1) mode |= AC_W_PROTECTED;
  1912.         } else {
  1913.             if (r == 1) mode |= AC_R_PRIVATE;
  1914.             if (w == 1) mode |= AC_W_PRIVATE;
  1915.         }
  1916.     }
  1917.     vmode = newintobject((long)mode);
  1918.     imode = com_addconst(c, vmode);
  1919.     XDECREF(vmode);
  1920.     for (i = 1; TYPE(CHILD(n,i-1)) != COLON; i+=2) {
  1921.         com_addoparg(c, LOAD_CONST, imode);
  1922.         com_addopname(c, ACCESS_MODE, CHILD(n, i));
  1923.     }
  1924. }
  1925. #endif
  1926.  
  1927. static void
  1928. com_exec_stmt(c, n)
  1929.     struct compiling *c;
  1930.     node *n;
  1931. {
  1932.     REQ(n, exec_stmt);
  1933.     /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
  1934.     com_node(c, CHILD(n, 1));
  1935.     if (NCH(n) >= 4)
  1936.         com_node(c, CHILD(n, 3));
  1937.     else
  1938.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  1939.     if (NCH(n) >= 6)
  1940.         com_node(c, CHILD(n, 5));
  1941.     else
  1942.         com_addbyte(c, DUP_TOP);
  1943.     com_addbyte(c, EXEC_STMT);
  1944. }
  1945.  
  1946. static void
  1947. com_if_stmt(c, n)
  1948.     struct compiling *c;
  1949.     node *n;
  1950. {
  1951.     int i;
  1952.     int anchor = 0;
  1953.     REQ(n, if_stmt);
  1954.     /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
  1955.     for (i = 0; i+3 < NCH(n); i+=4) {
  1956.         int a = 0;
  1957.         node *ch = CHILD(n, i+1);
  1958.         if (i > 0)
  1959.             com_addoparg(c, SET_LINENO, ch->n_lineno);
  1960.         com_node(c, CHILD(n, i+1));
  1961.         com_addfwref(c, JUMP_IF_FALSE, &a);
  1962.         com_addbyte(c, POP_TOP);
  1963.         com_node(c, CHILD(n, i+3));
  1964.         com_addfwref(c, JUMP_FORWARD, &anchor);
  1965.         com_backpatch(c, a);
  1966.         com_addbyte(c, POP_TOP);
  1967.     }
  1968.     if (i+2 < NCH(n))
  1969.         com_node(c, CHILD(n, i+2));
  1970.     com_backpatch(c, anchor);
  1971. }
  1972.  
  1973. static void
  1974. com_while_stmt(c, n)
  1975.     struct compiling *c;
  1976.     node *n;
  1977. {
  1978.     int break_anchor = 0;
  1979.     int anchor = 0;
  1980.     int save_begin = c->c_begin;
  1981.     REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */
  1982.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  1983.     block_push(c, SETUP_LOOP);
  1984.     c->c_begin = c->c_nexti;
  1985.     com_addoparg(c, SET_LINENO, n->n_lineno);
  1986.     com_node(c, CHILD(n, 1));
  1987.     com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1988.     com_addbyte(c, POP_TOP);
  1989.     c->c_loops++;
  1990.     com_node(c, CHILD(n, 3));
  1991.     c->c_loops--;
  1992.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  1993.     c->c_begin = save_begin;
  1994.     com_backpatch(c, anchor);
  1995.     com_addbyte(c, POP_TOP);
  1996.     com_addbyte(c, POP_BLOCK);
  1997.     block_pop(c, SETUP_LOOP);
  1998.     if (NCH(n) > 4)
  1999.         com_node(c, CHILD(n, 6));
  2000.     com_backpatch(c, break_anchor);
  2001. }
  2002.  
  2003. static void
  2004. com_for_stmt(c, n)
  2005.     struct compiling *c;
  2006.     node *n;
  2007. {
  2008.     object *v;
  2009.     int break_anchor = 0;
  2010.     int anchor = 0;
  2011.     int save_begin = c->c_begin;
  2012.     REQ(n, for_stmt);
  2013.     /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
  2014.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2015.     block_push(c, SETUP_LOOP);
  2016.     com_node(c, CHILD(n, 3));
  2017.     v = newintobject(0L);
  2018.     if (v == NULL)
  2019.         c->c_errors++;
  2020.     com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  2021.     XDECREF(v);
  2022.     c->c_begin = c->c_nexti;
  2023.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2024.     com_addfwref(c, FOR_LOOP, &anchor);
  2025.     com_assign(c, CHILD(n, 1), OP_ASSIGN);
  2026.     c->c_loops++;
  2027.     com_node(c, CHILD(n, 5));
  2028.     c->c_loops--;
  2029.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2030.     c->c_begin = save_begin;
  2031.     com_backpatch(c, anchor);
  2032.     com_addbyte(c, POP_BLOCK);
  2033.     block_pop(c, SETUP_LOOP);
  2034.     if (NCH(n) > 8)
  2035.         com_node(c, CHILD(n, 8));
  2036.     com_backpatch(c, break_anchor);
  2037. }
  2038.  
  2039. /* Code generated for "try: S finally: Sf" is as follows:
  2040.    
  2041.         SETUP_FINALLY    L
  2042.         <code for S>
  2043.         POP_BLOCK
  2044.         LOAD_CONST    <nil>
  2045.     L:    <code for Sf>
  2046.         END_FINALLY
  2047.    
  2048.    The special instructions use the block stack.  Each block
  2049.    stack entry contains the instruction that created it (here
  2050.    SETUP_FINALLY), the level of the value stack at the time the
  2051.    block stack entry was created, and a label (here L).
  2052.    
  2053.    SETUP_FINALLY:
  2054.     Pushes the current value stack level and the label
  2055.     onto the block stack.
  2056.    POP_BLOCK:
  2057.     Pops en entry from the block stack, and pops the value
  2058.     stack until its level is the same as indicated on the
  2059.     block stack.  (The label is ignored.)
  2060.    END_FINALLY:
  2061.     Pops a variable number of entries from the *value* stack
  2062.     and re-raises the exception they specify.  The number of
  2063.     entries popped depends on the (pseudo) exception type.
  2064.    
  2065.    The block stack is unwound when an exception is raised:
  2066.    when a SETUP_FINALLY entry is found, the exception is pushed
  2067.    onto the value stack (and the exception condition is cleared),
  2068.    and the interpreter jumps to the label gotten from the block
  2069.    stack.
  2070.    
  2071.    Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
  2072.    (The contents of the value stack is shown in [], with the top
  2073.    at the right; 'tb' is trace-back info, 'val' the exception's
  2074.    associated value, and 'exc' the exception.)
  2075.    
  2076.    Value stack        Label    Instruction    Argument
  2077.    []                SETUP_EXCEPT    L1
  2078.    []                <code for S>
  2079.    []                POP_BLOCK
  2080.    []                JUMP_FORWARD    L0
  2081.    
  2082.    [tb, val, exc]    L1:    DUP                )
  2083.    [tb, val, exc, exc]        <evaluate E1>            )
  2084.    [tb, val, exc, exc, E1]    COMPARE_OP    EXC_MATCH    ) only if E1
  2085.    [tb, val, exc, 1-or-0]    JUMP_IF_FALSE    L2        )
  2086.    [tb, val, exc, 1]        POP                )
  2087.    [tb, val, exc]        POP
  2088.    [tb, val]            <assign to V1>    (or POP if no V1)
  2089.    [tb]                POP
  2090.    []                <code for S1>
  2091.                    JUMP_FORWARD    L0
  2092.    
  2093.    [tb, val, exc, 0]    L2:    POP
  2094.    [tb, val, exc]        DUP
  2095.    .............................etc.......................
  2096.  
  2097.    [tb, val, exc, 0]    Ln+1:    POP
  2098.    [tb, val, exc]           END_FINALLY    # re-raise exception
  2099.    
  2100.    []            L0:    <next statement>
  2101.    
  2102.    Of course, parts are not generated if Vi or Ei is not present.
  2103. */
  2104.  
  2105. static void
  2106. com_try_except(c, n)
  2107.     struct compiling *c;
  2108.     node *n;
  2109. {
  2110.     int except_anchor = 0;
  2111.     int end_anchor = 0;
  2112.     int else_anchor = 0;
  2113.     int i;
  2114.     node *ch;
  2115.  
  2116.     com_addfwref(c, SETUP_EXCEPT, &except_anchor);
  2117.     block_push(c, SETUP_EXCEPT);
  2118.     com_node(c, CHILD(n, 2));
  2119.     com_addbyte(c, POP_BLOCK);
  2120.     block_pop(c, SETUP_EXCEPT);
  2121.     com_addfwref(c, JUMP_FORWARD, &else_anchor);
  2122.     com_backpatch(c, except_anchor);
  2123.     for (i = 3;
  2124.          i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause;
  2125.          i += 3) {
  2126.         /* except_clause: 'except' [expr [',' expr]] */
  2127.         if (except_anchor == 0) {
  2128.             com_error(c, SyntaxError,
  2129.                   "default 'except:' must be last");
  2130.             break;
  2131.         }
  2132.         except_anchor = 0;
  2133.         com_addoparg(c, SET_LINENO, ch->n_lineno);
  2134.         if (NCH(ch) > 1) {
  2135.             com_addbyte(c, DUP_TOP);
  2136.             com_node(c, CHILD(ch, 1));
  2137.             com_addoparg(c, COMPARE_OP, EXC_MATCH);
  2138.             com_addfwref(c, JUMP_IF_FALSE, &except_anchor);
  2139.             com_addbyte(c, POP_TOP);
  2140.         }
  2141.         com_addbyte(c, POP_TOP);
  2142.         if (NCH(ch) > 3)
  2143.             com_assign(c, CHILD(ch, 3), OP_ASSIGN);
  2144.         else
  2145.             com_addbyte(c, POP_TOP);
  2146.         com_addbyte(c, POP_TOP);
  2147.         com_node(c, CHILD(n, i+2));
  2148.         com_addfwref(c, JUMP_FORWARD, &end_anchor);
  2149.         if (except_anchor) {
  2150.             com_backpatch(c, except_anchor);
  2151.             com_addbyte(c, POP_TOP);
  2152.         }
  2153.     }
  2154.     com_addbyte(c, END_FINALLY);
  2155.     com_backpatch(c, else_anchor);
  2156.     if (i < NCH(n))
  2157.         com_node(c, CHILD(n, i+2));
  2158.     com_backpatch(c, end_anchor);
  2159. }
  2160.  
  2161. static void
  2162. com_try_finally(c, n)
  2163.     struct compiling *c;
  2164.     node *n;
  2165. {
  2166.     int finally_anchor = 0;
  2167.     node *ch;
  2168.  
  2169.     com_addfwref(c, SETUP_FINALLY, &finally_anchor);
  2170.     block_push(c, SETUP_FINALLY);
  2171.     com_node(c, CHILD(n, 2));
  2172.     com_addbyte(c, POP_BLOCK);
  2173.     block_pop(c, SETUP_FINALLY);
  2174.     block_push(c, END_FINALLY);
  2175.     com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2176.     com_backpatch(c, finally_anchor);
  2177.     ch = CHILD(n, NCH(n)-1);
  2178.     com_addoparg(c, SET_LINENO, ch->n_lineno);
  2179.     com_node(c, ch);
  2180.     com_addbyte(c, END_FINALLY);
  2181.     block_pop(c, END_FINALLY);
  2182. }
  2183.  
  2184. static void
  2185. com_try_stmt(c, n)
  2186.     struct compiling *c;
  2187.     node *n;
  2188. {
  2189.     REQ(n, try_stmt);
  2190.     /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  2191.      | 'try' ':' suite 'finally' ':' suite */
  2192.     if (TYPE(CHILD(n, 3)) != except_clause)
  2193.         com_try_finally(c, n);
  2194.     else
  2195.         com_try_except(c, n);
  2196. }
  2197.  
  2198. static object *
  2199. get_docstring(n)
  2200.     node *n;
  2201. {
  2202.     int i;
  2203.  
  2204.     switch (TYPE(n)) {
  2205.  
  2206.     case suite:
  2207.         if (NCH(n) == 1)
  2208.             return get_docstring(CHILD(n, 0));
  2209.         else {
  2210.             for (i = 0; i < NCH(n); i++) {
  2211.                 node *ch = CHILD(n, i);
  2212.                 if (TYPE(ch) == stmt)
  2213.                     return get_docstring(ch);
  2214.             }
  2215.         }
  2216.         break;
  2217.  
  2218.     case file_input:
  2219.         for (i = 0; i < NCH(n); i++) {
  2220.             node *ch = CHILD(n, i);
  2221.             if (TYPE(ch) == stmt)
  2222.                 return get_docstring(ch);
  2223.         }
  2224.         break;
  2225.  
  2226.     case stmt:
  2227.     case simple_stmt:
  2228.     case small_stmt:
  2229.         return get_docstring(CHILD(n, 0));
  2230.  
  2231.     case expr_stmt:
  2232.     case testlist:
  2233.     case test:
  2234.     case and_test:
  2235.     case not_test:
  2236.     case comparison:
  2237.     case expr:
  2238.     case xor_expr:
  2239.     case and_expr:
  2240.     case shift_expr:
  2241.     case arith_expr:
  2242.     case term:
  2243.     case factor:
  2244.     case power:
  2245.         if (NCH(n) == 1)
  2246.             return get_docstring(CHILD(n, 0));
  2247.         break;
  2248.  
  2249.     case atom:
  2250.         if (TYPE(CHILD(n, 0)) == STRING)
  2251.             return parsestrplus(n);
  2252.         break;
  2253.  
  2254.     }
  2255.     return NULL;
  2256. }
  2257.  
  2258. static void
  2259. com_suite(c, n)
  2260.     struct compiling *c;
  2261.     node *n;
  2262. {
  2263.     REQ(n, suite);
  2264.     /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
  2265.     if (NCH(n) == 1) {
  2266.         com_node(c, CHILD(n, 0));
  2267.     }
  2268.     else {
  2269.         int i;
  2270.         for (i = 0; i < NCH(n); i++) {
  2271.             node *ch = CHILD(n, i);
  2272.             if (TYPE(ch) == stmt)
  2273.                 com_node(c, ch);
  2274.         }
  2275.     }
  2276. }
  2277.  
  2278. /* ARGSUSED */
  2279. static void
  2280. com_continue_stmt(c, n)
  2281.     struct compiling *c;
  2282.     node *n; /* Not used, but passed for consistency */
  2283. {
  2284.     int i = c->c_nblocks;
  2285.     if (i-- > 0 && c->c_block[i] == SETUP_LOOP) {
  2286.         com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2287.     }
  2288.     else {
  2289.         com_error(c, SyntaxError, "'continue' not properly in loop");
  2290.     }
  2291.     /* XXX Could allow it inside a 'finally' clause
  2292.        XXX if we could pop the exception still on the stack */
  2293. }
  2294.  
  2295. static int
  2296. com_argdefs(c, n)
  2297.     struct compiling *c;
  2298.     node *n;
  2299. {
  2300.     int i, nch, nargs, ndefs;
  2301.     if (TYPE(n) == lambdef) {
  2302.         /* lambdef: 'lambda' [varargslist] ':' test */
  2303.         n = CHILD(n, 1);
  2304.     }
  2305.     else {
  2306.         REQ(n, funcdef); /* funcdef: 'def' NAME parameters ... */
  2307.         n = CHILD(n, 2);
  2308.         REQ(n, parameters); /* parameters: '(' [varargslist] ')' */
  2309.         n = CHILD(n, 1);
  2310.     }
  2311.     if (TYPE(n) != varargslist)
  2312.             return 0;
  2313.     /* varargslist:
  2314.         (fpdef ['=' test] ',')* '*' ....... |
  2315.         fpdef ['=' test] (',' fpdef ['=' test])* [','] */
  2316.     nch = NCH(n);
  2317.     nargs = 0;
  2318.     ndefs = 0;
  2319.     for (i = 0; i < nch; i++) {
  2320.         int t;
  2321.         if (TYPE(CHILD(n, i)) == STAR || TYPE(CHILD(n, i)) == DOUBLESTAR)
  2322.             break;
  2323.         nargs++;
  2324.         i++;
  2325.         if (i >= nch)
  2326.             t = RPAR; /* Anything except EQUAL or COMMA */
  2327.         else
  2328.             t = TYPE(CHILD(n, i));
  2329.         if (t == EQUAL) {
  2330.             i++;
  2331.             ndefs++;
  2332.             com_node(c, CHILD(n, i));
  2333.             i++;
  2334.             if (i >= nch)
  2335.                 break;
  2336.             t = TYPE(CHILD(n, i));
  2337.         }
  2338.         else {
  2339.             /* Treat "(a=1, b)" as "(a=1, b=None)" */
  2340.             if (ndefs) {
  2341.                 com_addoparg(c, LOAD_CONST,
  2342.                          com_addconst(c, None));
  2343.                 ndefs++;
  2344.             }
  2345.         }
  2346.         if (t != COMMA)
  2347.             break;
  2348.     }
  2349.     return ndefs;
  2350. }
  2351.  
  2352. static void
  2353. com_funcdef(c, n)
  2354.     struct compiling *c;
  2355.     node *n;
  2356. {
  2357.     object *v;
  2358.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  2359.     v = (object *)icompile(n, c);
  2360.     if (v == NULL)
  2361.         c->c_errors++;
  2362.     else {
  2363.         int i = com_addconst(c, v);
  2364.         int ndefs = com_argdefs(c, n);
  2365.         com_addoparg(c, LOAD_CONST, i);
  2366.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  2367.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2368.         DECREF(v);
  2369.     }
  2370. }
  2371.  
  2372. static void
  2373. com_bases(c, n)
  2374.     struct compiling *c;
  2375.     node *n;
  2376. {
  2377.     int i;
  2378.     REQ(n, testlist);
  2379.     /* testlist: test (',' test)* [','] */
  2380.     for (i = 0; i < NCH(n); i += 2)
  2381.         com_node(c, CHILD(n, i));
  2382.     com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 2);
  2383. }
  2384.  
  2385. static void
  2386. com_classdef(c, n)
  2387.     struct compiling *c;
  2388.     node *n;
  2389. {
  2390.     int i;
  2391.     object *v;
  2392.     REQ(n, classdef);
  2393.     /* classdef: class NAME ['(' testlist ')'] ':' suite */
  2394.     if ((v = newstringobject(STR(CHILD(n, 1)))) == NULL) {
  2395.         c->c_errors++;
  2396.         return;
  2397.     }
  2398.     /* Push the class name on the stack */
  2399.     i = com_addconst(c, v);
  2400.     com_addoparg(c, LOAD_CONST, i);
  2401.     DECREF(v);
  2402.     /* Push the tuple of base classes on the stack */
  2403.     if (TYPE(CHILD(n, 2)) != LPAR)
  2404.         com_addoparg(c, BUILD_TUPLE, 0);
  2405.     else
  2406.         com_bases(c, CHILD(n, 3));
  2407.     v = (object *)icompile(n, c);
  2408.     if (v == NULL)
  2409.         c->c_errors++;
  2410.     else {
  2411.         i = com_addconst(c, v);
  2412.         com_addoparg(c, LOAD_CONST, i);
  2413.         com_addoparg(c, MAKE_FUNCTION, 0);
  2414.         com_addoparg(c, CALL_FUNCTION, 0);
  2415.         com_addbyte(c, BUILD_CLASS);
  2416.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2417.         DECREF(v);
  2418.     }
  2419. }
  2420.  
  2421. static void
  2422. com_node(c, n)
  2423.     struct compiling *c;
  2424.     node *n;
  2425. {
  2426.     switch (TYPE(n)) {
  2427.     
  2428.     /* Definition nodes */
  2429.     
  2430.     case funcdef:
  2431.         com_funcdef(c, n);
  2432.         break;
  2433.     case classdef:
  2434.         com_classdef(c, n);
  2435.         break;
  2436.     
  2437.     /* Trivial parse tree nodes */
  2438.     
  2439.     case stmt:
  2440.     case small_stmt:
  2441.     case flow_stmt:
  2442.         com_node(c, CHILD(n, 0));
  2443.         break;
  2444.  
  2445.     case simple_stmt:
  2446.         /* small_stmt (';' small_stmt)* [';'] NEWLINE */
  2447.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2448.         {
  2449.             int i;
  2450.             for (i = 0; i < NCH(n)-1; i += 2)
  2451.                 com_node(c, CHILD(n, i));
  2452.         }
  2453.         break;
  2454.     
  2455.     case compound_stmt:
  2456.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2457.         com_node(c, CHILD(n, 0));
  2458.         break;
  2459.  
  2460.     /* Statement nodes */
  2461.     
  2462.     case expr_stmt:
  2463.         com_expr_stmt(c, n);
  2464.         break;
  2465.     case print_stmt:
  2466.         com_print_stmt(c, n);
  2467.         break;
  2468.     case del_stmt: /* 'del' exprlist */
  2469.         com_assign(c, CHILD(n, 1), OP_DELETE);
  2470.         break;
  2471.     case pass_stmt:
  2472.         break;
  2473.     case break_stmt:
  2474.         if (c->c_loops == 0) {
  2475.             com_error(c, SyntaxError, "'break' outside loop");
  2476.         }
  2477.         com_addbyte(c, BREAK_LOOP);
  2478.         break;
  2479.     case continue_stmt:
  2480.         com_continue_stmt(c, n);
  2481.         break;
  2482.     case return_stmt:
  2483.         com_return_stmt(c, n);
  2484.         break;
  2485.     case raise_stmt:
  2486.         com_raise_stmt(c, n);
  2487.         break;
  2488.     case import_stmt:
  2489.         com_import_stmt(c, n);
  2490.         break;
  2491.     case global_stmt:
  2492.         com_global_stmt(c, n);
  2493.         break;
  2494. #ifdef SUPPORT_OBSOLETE_ACCESS
  2495.     case access_stmt:
  2496.         com_access_stmt(c, n);
  2497.         break;
  2498. #endif
  2499.     case exec_stmt:
  2500.         com_exec_stmt(c, n);
  2501.         break;
  2502.     case if_stmt:
  2503.         com_if_stmt(c, n);
  2504.         break;
  2505.     case while_stmt:
  2506.         com_while_stmt(c, n);
  2507.         break;
  2508.     case for_stmt:
  2509.         com_for_stmt(c, n);
  2510.         break;
  2511.     case try_stmt:
  2512.         com_try_stmt(c, n);
  2513.         break;
  2514.     case suite:
  2515.         com_suite(c, n);
  2516.         break;
  2517.     
  2518.     /* Expression nodes */
  2519.     
  2520.     case testlist:
  2521.         com_list(c, n, 0);
  2522.         break;
  2523.     case test:
  2524.         com_test(c, n);
  2525.         break;
  2526.     case and_test:
  2527.         com_and_test(c, n);
  2528.         break;
  2529.     case not_test:
  2530.         com_not_test(c, n);
  2531.         break;
  2532.     case comparison:
  2533.         com_comparison(c, n);
  2534.         break;
  2535.     case exprlist:
  2536.         com_list(c, n, 0);
  2537.         break;
  2538.     case expr:
  2539.         com_expr(c, n);
  2540.         break;
  2541.     case xor_expr:
  2542.         com_xor_expr(c, n);
  2543.         break;
  2544.     case and_expr:
  2545.         com_and_expr(c, n);
  2546.         break;
  2547.     case shift_expr:
  2548.         com_shift_expr(c, n);
  2549.         break;
  2550.     case arith_expr:
  2551.         com_arith_expr(c, n);
  2552.         break;
  2553.     case term:
  2554.         com_term(c, n);
  2555.         break;
  2556.     case factor:
  2557.         com_factor(c, n);
  2558.         break;
  2559.     case power:
  2560.         com_power(c, n);
  2561.         break;
  2562.     case atom:
  2563.         com_atom(c, n);
  2564.         break;
  2565.     
  2566.     default:
  2567.         fprintf(stderr, "node type %d\n", TYPE(n));
  2568.         com_error(c, SystemError, "com_node: unexpected node type");
  2569.     }
  2570. }
  2571.  
  2572. static void com_fplist PROTO((struct compiling *, node *));
  2573.  
  2574. static void
  2575. com_fpdef(c, n)
  2576.     struct compiling *c;
  2577.     node *n;
  2578. {
  2579.     REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2580.     if (TYPE(CHILD(n, 0)) == LPAR)
  2581.         com_fplist(c, CHILD(n, 1));
  2582.     else
  2583.         com_addoparg(c, STORE_FAST, com_newlocal(c, STR(CHILD(n, 0))));
  2584. }
  2585.  
  2586. static void
  2587. com_fplist(c, n)
  2588.     struct compiling *c;
  2589.     node *n;
  2590. {
  2591.     REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */
  2592.     if (NCH(n) == 1) {
  2593.         com_fpdef(c, CHILD(n, 0));
  2594.     }
  2595.     else {
  2596.         int i;
  2597.         com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2);
  2598.         for (i = 0; i < NCH(n); i += 2)
  2599.             com_fpdef(c, CHILD(n, i));
  2600.     }
  2601. }
  2602.  
  2603. static void
  2604. com_arglist(c, n)
  2605.     struct compiling *c;
  2606.     node *n;
  2607. {
  2608.     int nch, i;
  2609.     int complex = 0;
  2610.     REQ(n, varargslist);
  2611.     /* varargslist:
  2612.         (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
  2613.     nch = NCH(n);
  2614.     /* Enter all arguments in table of locals */
  2615.     for (i = 0; i < nch; i++) {
  2616.         node *ch = CHILD(n, i);
  2617.         node *fp;
  2618.         char *name;
  2619.         if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  2620.             break;
  2621.         REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2622.         fp = CHILD(ch, 0);
  2623.         if (TYPE(fp) == NAME)
  2624.             name = STR(fp);
  2625.         else {
  2626.             name = "";
  2627.             complex = 1;
  2628.         }
  2629.         com_newlocal(c, name);
  2630.         c->c_argcount++;
  2631.         if (++i >= nch)
  2632.             break;
  2633.         ch = CHILD(n, i);
  2634.         if (TYPE(ch) == EQUAL)
  2635.             i += 2;
  2636.         else
  2637.             REQ(ch, COMMA);
  2638.     }
  2639.     /* Handle *arguments */
  2640.     if (i < nch) {
  2641.         node *ch;
  2642.         ch = CHILD(n, i);
  2643.         if (TYPE(ch) != DOUBLESTAR) {
  2644.             REQ(ch, STAR);
  2645.             ch = CHILD(n, i+1);
  2646.             if (TYPE(ch) == NAME) {
  2647.                 c->c_flags |= CO_VARARGS;
  2648.                 i += 3;
  2649.                 com_newlocal(c, STR(ch));
  2650.             }
  2651.         }
  2652.     }
  2653.     /* Handle **keywords */
  2654.     if (i < nch) {
  2655.         node *ch;
  2656.         ch = CHILD(n, i);
  2657.         if (TYPE(ch) != DOUBLESTAR) {
  2658.             REQ(ch, STAR);
  2659.             ch = CHILD(n, i+1);
  2660.             REQ(ch, STAR);
  2661.             ch = CHILD(n, i+2);
  2662.         }
  2663.         else
  2664.             ch = CHILD(n, i+1);
  2665.         REQ(ch, NAME);
  2666.         c->c_flags |= CO_VARKEYWORDS;
  2667.         com_newlocal(c, STR(ch));
  2668.     }
  2669.     if (complex) {
  2670.         /* Generate code for complex arguments only after
  2671.            having counted the simple arguments */
  2672.         int ilocal = 0;
  2673.         for (i = 0; i < nch; i++) {
  2674.             node *ch = CHILD(n, i);
  2675.             node *fp;
  2676.             if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  2677.                 break;
  2678.             REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2679.             fp = CHILD(ch, 0);
  2680.             if (TYPE(fp) != NAME) {
  2681.                 com_addoparg(c, LOAD_FAST, ilocal);
  2682.                 com_fpdef(c, ch);
  2683.             }
  2684.             ilocal++;
  2685.             if (++i >= nch)
  2686.                 break;
  2687.             ch = CHILD(n, i);
  2688.             if (TYPE(ch) == EQUAL)
  2689.                 i += 2;
  2690.             else
  2691.                 REQ(ch, COMMA);
  2692.         }
  2693.     }
  2694. }
  2695.  
  2696. static void
  2697. com_file_input(c, n)
  2698.     struct compiling *c;
  2699.     node *n;
  2700. {
  2701.     int i;
  2702.     object *doc;
  2703.     REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */
  2704.     doc = get_docstring(n);
  2705.     if (doc != NULL) {
  2706.         int i = com_addconst(c, doc);
  2707.         DECREF(doc);
  2708.         com_addoparg(c, LOAD_CONST, i);
  2709.         com_addopnamestr(c, STORE_NAME, "__doc__");
  2710.     }
  2711.     for (i = 0; i < NCH(n); i++) {
  2712.         node *ch = CHILD(n, i);
  2713.         if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE)
  2714.             com_node(c, ch);
  2715.     }
  2716. }
  2717.  
  2718. /* Top-level compile-node interface */
  2719.  
  2720. static void
  2721. compile_funcdef(c, n)
  2722.     struct compiling *c;
  2723.     node *n;
  2724. {
  2725.     object *doc;
  2726.     node *ch;
  2727.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  2728.     c->c_name = STR(CHILD(n, 1));
  2729.     doc = get_docstring(CHILD(n, 4));
  2730.     if (doc != NULL) {
  2731.         (void) com_addconst(c, doc);
  2732.         DECREF(doc);
  2733.     }
  2734.     else
  2735.         (void) com_addconst(c, None); /* No docstring */
  2736.     ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */
  2737.     ch = CHILD(ch, 1); /* ')' | varargslist */
  2738.     if (TYPE(ch) == varargslist)
  2739.         com_arglist(c, ch);
  2740.     c->c_infunction = 1;
  2741.     com_node(c, CHILD(n, 4));
  2742.     c->c_infunction = 0;
  2743.     com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2744.     com_addbyte(c, RETURN_VALUE);
  2745. }
  2746.  
  2747. static void
  2748. compile_lambdef(c, n)
  2749.     struct compiling *c;
  2750.     node *n;
  2751. {
  2752.     node *ch;
  2753.     REQ(n, lambdef); /* lambdef: 'lambda' [varargslist] ':' test */
  2754.     c->c_name = "<lambda>";
  2755.  
  2756.     ch = CHILD(n, 1);
  2757.     (void) com_addconst(c, None); /* No docstring */
  2758.     if (TYPE(ch) == varargslist) {
  2759.         com_arglist(c, ch);
  2760.         ch = CHILD(n, 3);
  2761.     }
  2762.     else
  2763.         ch = CHILD(n, 2);
  2764.     com_node(c, ch);
  2765.     com_addbyte(c, RETURN_VALUE);
  2766. }
  2767.  
  2768. static void
  2769. compile_classdef(c, n)
  2770.     struct compiling *c;
  2771.     node *n;
  2772. {
  2773.     node *ch;
  2774.     object *doc;
  2775.     REQ(n, classdef);
  2776.     /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
  2777.     c->c_name = STR(CHILD(n, 1));
  2778. #ifdef PRIVATE_NAME_MANGLING
  2779.     c->c_private = c->c_name;
  2780. #endif
  2781.     ch = CHILD(n, NCH(n)-1); /* The suite */
  2782.     doc = get_docstring(ch);
  2783.     if (doc != NULL) {
  2784.         int i = com_addconst(c, doc);
  2785.         DECREF(doc);
  2786.         com_addoparg(c, LOAD_CONST, i);
  2787.         com_addopnamestr(c, STORE_NAME, "__doc__");
  2788.     }
  2789.     else
  2790.         (void) com_addconst(c, None);
  2791.     com_node(c, ch);
  2792.     com_addbyte(c, LOAD_LOCALS);
  2793.     com_addbyte(c, RETURN_VALUE);
  2794. }
  2795.  
  2796. static void
  2797. compile_node(c, n)
  2798.     struct compiling *c;
  2799.     node *n;
  2800. {
  2801.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2802.     
  2803.     switch (TYPE(n)) {
  2804.     
  2805.     case single_input: /* One interactive command */
  2806.         /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
  2807.         c->c_interactive++;
  2808.         n = CHILD(n, 0);
  2809.         if (TYPE(n) != NEWLINE)
  2810.             com_node(c, n);
  2811.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2812.         com_addbyte(c, RETURN_VALUE);
  2813.         c->c_interactive--;
  2814.         break;
  2815.     
  2816.     case file_input: /* A whole file, or built-in function exec() */
  2817.         com_file_input(c, n);
  2818.         com_addoparg(c, LOAD_CONST, com_addconst(c, None));
  2819.         com_addbyte(c, RETURN_VALUE);
  2820.         break;
  2821.     
  2822.     case eval_input: /* Built-in function input() */
  2823.         com_node(c, CHILD(n, 0));
  2824.         com_addbyte(c, RETURN_VALUE);
  2825.         break;
  2826.     
  2827.     case lambdef: /* anonymous function definition */
  2828.         compile_lambdef(c, n);
  2829.         break;
  2830.  
  2831.     case funcdef: /* A function definition */
  2832.         compile_funcdef(c, n);
  2833.         break;
  2834.     
  2835.     case classdef: /* A class definition */
  2836.         compile_classdef(c, n);
  2837.         break;
  2838.     
  2839.     default:
  2840.         fprintf(stderr, "node type %d\n", TYPE(n));
  2841.         com_error(c, SystemError,
  2842.               "compile_node: unexpected node type");
  2843.     }
  2844. }
  2845.  
  2846. /* Optimization for local variables in functions (and *only* functions).
  2847.  
  2848.    This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
  2849.    instructions that refer to local variables with LOAD_FAST etc.
  2850.    The latter instructions are much faster because they don't need to
  2851.    look up the variable name in a dictionary.
  2852.  
  2853.    To find all local variables, we check all STORE_NAME, IMPORT_FROM
  2854.    and DELETE_NAME instructions.  This yields all local variables,
  2855.    function definitions, class definitions and import statements.
  2856.    Argument names have already been entered into the list by the
  2857.    special processing for the argument list.
  2858.  
  2859.    All remaining LOAD_NAME instructions must refer to non-local (global
  2860.    or builtin) variables, so are replaced by LOAD_GLOBAL.
  2861.  
  2862.    There are two problems:  'from foo import *' and 'exec' may introduce
  2863.    local variables that we can't know while compiling.  If this is the
  2864.    case, we can still optimize bona fide locals (since those
  2865.    statements will be surrounded by fast_2_locals() and
  2866.    locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL.
  2867.  
  2868.    NB: this modifies the string object c->c_code!  */
  2869.  
  2870. static void
  2871. optimize(c)
  2872.     struct compiling *c;
  2873. {
  2874.     unsigned char *next_instr, *cur_instr;
  2875.     int opcode;
  2876.     int oparg;
  2877.     object *name;
  2878.     object *error_type, *error_value, *error_traceback;
  2879.     
  2880. #define NEXTOP()    (*next_instr++)
  2881. #define NEXTARG()    (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
  2882. #define GETITEM(v, i)    (getlistitem((v), (i)))
  2883. #define GETNAMEOBJ(i)    (GETITEM(c->c_names, (i)))
  2884.     
  2885.     err_fetch(&error_type, &error_value, &error_traceback);
  2886.  
  2887.     c->c_flags |= CO_OPTIMIZED;
  2888.     
  2889.     next_instr = (unsigned char *) getstringvalue(c->c_code);
  2890.     for (;;) {
  2891.         opcode = NEXTOP();
  2892.         if (opcode == STOP_CODE)
  2893.             break;
  2894.         if (HAS_ARG(opcode))
  2895.             oparg = NEXTARG();
  2896.         switch (opcode) {
  2897.         case STORE_NAME:
  2898.         case DELETE_NAME:
  2899.         case IMPORT_FROM:
  2900.             com_addlocal_o(c, GETNAMEOBJ(oparg));
  2901.             break;
  2902.         case EXEC_STMT:
  2903.             c->c_flags &= ~CO_OPTIMIZED;
  2904.             break;
  2905.         }
  2906.     }
  2907.     
  2908.     if (dictlookup(c->c_locals, "*") != NULL)
  2909.         c->c_flags &= ~CO_OPTIMIZED;
  2910.     
  2911.     next_instr = (unsigned char *) getstringvalue(c->c_code);
  2912.     for (;;) {
  2913.         cur_instr = next_instr;
  2914.         opcode = NEXTOP();
  2915.         if (opcode == STOP_CODE)
  2916.             break;
  2917.         if (HAS_ARG(opcode))
  2918.             oparg = NEXTARG();
  2919.         if (opcode == LOAD_NAME ||
  2920.             opcode == STORE_NAME ||
  2921.             opcode == DELETE_NAME) {
  2922.             object *v;
  2923.             int i;
  2924.             name = GETNAMEOBJ(oparg);
  2925.             v = dict2lookup(c->c_locals, name);
  2926.             if (v == NULL) {
  2927.                 err_clear();
  2928.                 if (opcode == LOAD_NAME &&
  2929.                     (c->c_flags&CO_OPTIMIZED))
  2930.                     cur_instr[0] = LOAD_GLOBAL;
  2931.                 continue;
  2932.             }
  2933.             i = getintvalue(v);
  2934.             switch (opcode) {
  2935.             case LOAD_NAME: cur_instr[0] = LOAD_FAST; break;
  2936.             case STORE_NAME: cur_instr[0] = STORE_FAST; break;
  2937.             case DELETE_NAME: cur_instr[0] = DELETE_FAST; break;
  2938.             }
  2939.             cur_instr[1] = i & 0xff;
  2940.             cur_instr[2] = (i>>8) & 0xff;
  2941.         }
  2942.     }
  2943.  
  2944.     if (c->c_errors == 0)
  2945.         err_restore(error_type, error_value, error_traceback);
  2946. }
  2947.  
  2948. codeobject *
  2949. compile(n, filename)
  2950.     node *n;
  2951.     char *filename;
  2952. {
  2953.     return jcompile(n, filename, NULL);
  2954. }
  2955.  
  2956. static codeobject *
  2957. icompile(n, base)
  2958.     node *n;
  2959.     struct compiling *base;
  2960. {
  2961.     return jcompile(n, base->c_filename, base);
  2962. }
  2963.  
  2964. static codeobject *
  2965. jcompile(n, filename, base)
  2966.     node *n;
  2967.     char *filename;
  2968.     struct compiling *base;
  2969. {
  2970.     struct compiling sc;
  2971.     codeobject *co;
  2972.     if (!com_init(&sc, filename))
  2973.         return NULL;
  2974. #ifdef PRIVATE_NAME_MANGLING
  2975.     if (base)
  2976.         sc.c_private = base->c_private;
  2977.     else
  2978.         sc.c_private = NULL;
  2979. #endif
  2980.     compile_node(&sc, n);
  2981.     com_done(&sc);
  2982.     if ((TYPE(n) == funcdef || TYPE(n) == lambdef) && sc.c_errors == 0) {
  2983.         optimize(&sc);
  2984.         sc.c_flags |= CO_NEWLOCALS;
  2985.     }
  2986.     else if (TYPE(n) == classdef)
  2987.         sc.c_flags |= CO_NEWLOCALS;
  2988.     co = NULL;
  2989.     if (sc.c_errors == 0) {
  2990.         object *consts, *names, *varnames, *filename, *name;
  2991.         consts = listtuple(sc.c_consts);
  2992.         names = listtuple(sc.c_names);
  2993.         varnames = listtuple(sc.c_varnames);
  2994.         filename = newstringobject(sc.c_filename);
  2995.         name = newstringobject(sc.c_name);
  2996.         if (!err_occurred())
  2997.             co = newcodeobject(sc.c_argcount,
  2998.                        sc.c_nlocals,
  2999.                        sc.c_flags,
  3000.                        sc.c_code,
  3001.                        consts,
  3002.                        names,
  3003.                        varnames,
  3004.                        filename,
  3005.                        name);
  3006.         XDECREF(consts);
  3007.         XDECREF(names);
  3008.         XDECREF(varnames);
  3009.         XDECREF(filename);
  3010.         XDECREF(name);
  3011.     }
  3012.     com_free(&sc);
  3013.     return co;
  3014. }
  3015.